【问题标题】:react-native changes the properties of the elements in the array?react-native 改变数组中元素的属性?
【发布时间】:2019-07-26 10:58:47
【问题描述】:

我有一个FlatList,我想实现一个单选按钮。我的想法是更改this.state.data中元素的选定属性来控制它,但我是新手,我不知道如何更改this.state.data中元素的属性。

这是我的代码:

this.state = {
  data: [
    {
      month:1,
      price:18,
      selected:true
    },
    {
      month:3,
      price:48,
      selected:false
    },
    {
      month:12,
      price:128,
      selected:false
    },
  ],
};
<FlatList
  data={this.state.data}
  renderItem={({item, index, separators}) => (
    <TouchableOpacity onPress={() => this.radio(index,item)}>
    <View style={item.selected ? {borderWidth:3,borderColor:'#FFA371',borderRadius:15}:{}}>
      <View style={styles.itemDefalut}>
        <View style={{ flexDirection: "column", flex: 1 }}>
          <Text>
          Months
          </Text>
          <Text>{item.month} Months</Text>
        </View>
        <View>
          <Text>${item.price}</Text>
        </View>
      </View>
    </View>
    </TouchableOpacity>
  )}
/>
radio(index,item) {
  for (var variable in this.state.data) {
    variable.selected = false;
  }
  item.selected = true;
}

【问题讨论】:

    标签: react-native radio-button react-native-flatlist


    【解决方案1】:

    仅第一次通过 index 来自 onpress

    onPress={() => this.radio(index)
    

    然后在 radio 函数中做这样的事情

    radio = index => {
      let data = [ ...this.state.data ];
      this.state.data.map((elem,key)=>{
        if(elem.month==data[index].month){
           data[key]={...data[key], selected: true};
        }else{
         data[key]={...data[key], selected: false};
        }
      })
      this.setState({ data:data});
    }
    

    【讨论】:

      【解决方案2】:
      radio(item) {
        let data = [...this.state.data]; 
        let index = data.findIndex(el => el.month === item.month); 
        data[index] = {...data[index], selected: !item.selected};
        this.setState({ data });
      }
      

      在 TouchableOpacity on press 它应该是

      <TouchableOpacity onPress = {this.radio.bind(this,item)}>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-24
        • 2020-10-17
        • 2019-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多