简体   繁体   中英

React Native: Change and keep the background color of only onPressed item inside Flatlist

I've manage to change the background color of the onPressed button inside a Flatlist by assigning item.id to the state. My issue is that when I press another button the previously pressed button changes back to the initial backgroundcolor. How can I keep the new backgoundcolor even when I press another button?

 onPressButtonarrived(item.id) {
    this.setState({ disablearrived: item.id })
    this.setState({ colorarrived: item.id })
  }


<View style={{backgroundColor: item.id === this.state.colorarrived ? '#D6D6D6' : '#E5C454'}}>
    <TouchableOpacity
    onPress={() => {this.onPressButtonarrived(item.id)}} disabled={item.id === this.state.disablearrived ? true : false}>
    <Text>Arrival</Text>
</TouchableOpacity>

You need to have some values on state for each item:

 onPressButtonarrived(item.id) {
        this.setState({ [item.id +'-disablearrived']: !this.state[item.id] });
        this.setState({ [item.id +'-colorarrived']: !this.state[item.id] });
        // that should toggle some true false vars for each item.id 
      }


    <View style={{backgroundColor: this.state[item.id +'-colorarrived'] ? '#D6D6D6' : '#E5C454'}}>
        <TouchableOpacity
        onPress={() => {this.onPressButtonarrived(item.id)}} disabled={!!this.state[item.id +'-disablearrived']}>
        <Text>Arrival</Text>
    </TouchableOpacity>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM