【问题标题】:select single radio button in react native flatlist在反应原生平面列表中选择单个单选按钮
【发布时间】:2022-01-13 06:24:37
【问题描述】:

我是 React Native 初学者,正在使用 expo-radio-button。

但我无法在平面列表中一次选择一个单选按钮。

如果我选择单个按钮,它将只选择一个按钮。

帮我解决这个问题。 我需要在每个问题的单选按钮中显示并选择是或否

Click here to see output that i want

var myArray = [
  {
    isSignReq: "1",
    sno: "1",
    yesno: "0",
  },
  {
    isSignReq: "1",
    sno: "2",
    yesno: "0",
  },
  {
    isSignReq: "1",
    sno: "3",
    yesno: "0",
  },
];

const [account, setAccount] = useState([]);

const setFormSubmit = (val) => {
  console.log(val);
};

<FlatList
  data={myArray}
  keyExtractor={() => {
    return (
      new Date().getTime().toString() +
      Math.floor(Math.random() * Math.floor(new Date().getTime())).toString()
    );
  }}
  renderItem={(itemData) => {
    return (
      <View style={{ flexDirection: "row", marginVertical: "2%" }}>
        <Text style={styles.data1}>{itemData.item.sno}</Text>
        <Text style={styles.data2}>{itemData.item.name}</Text>
        <View style={{ width: "30%", marginLeft: "1%" }}>
          <RadioButtonGroup
            onSelected={(value) => {
              setFormSubmit(value), setAccount(value);
            }}
            selected={account}
            size={22}
            containerStyle={{ flexDirection: "row" }}
          >
            <RadioButtonItem label={"Yes"} value={itemData.item.isSignReq} />
            <RadioButtonItem label={"No"} value={itemData.item.yesno} />
          </RadioButtonGroup>
        </View>
      </View>
    );
  }}
/>

【问题讨论】:

    标签: javascript arrays react-native react-hooks


    【解决方案1】:
    renderItem = ({item, index}) => {
     .....
    <RadioButton
      innerColor={Colors.darkBlue}
      outerColor={Colors.lightGray}
      animation={'bounceIn'}enter code here
      isSelected={this.state.selectedIndex === index}
      onPress={() => {this.onPress(index)}}
    />
    }
    

    并将 onPress 替换为

    onPress = (index) => {
       this.setState({ selectedIndex: index });
     }
    

    并使用 extraData 道具更新 FlatList,因为 FlatList 需要重新渲染为

    <FlatList
       keyExtractor={this._keyExtractor}
       data={this.state.data}
       renderItem={this.renderItem}
       ItemSeparatorComponent={this.renderSeparator}
       extraData={this.state}
     />
    

    演示:https://snack.expo.dev/HkzA9cCSB

    【讨论】:

    • 兄弟,我需要 2 个按钮来回答是和否的每个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    相关资源
    最近更新 更多