简体   繁体   中英

How to toggle a single element coming from a map iteration in react native?

I have a toggle function to change a property in the state:

toggleSelected = () => {
    this.setState({selected:!this.state.selected})
  }

I also have a map function to iterate some data:

data.allRoomTypes.edges.map( c => 
<TouchableOpacity key={c.node.roomTypeId} onPress={this.toggleSelected}>  
   <Row style={styles.boxWithShadow}>
       <Col style={{marginLeft:160}}>
          <View style={{flex:1, flexDirection:"row"}}>
             {this.state.selected === false ? <Image style={styles.center} source={require("../../images/roomtypes/radio_btn_unselected.png")}/> : <Image style={styles.center} source={require("../../images/roomtypes/radio_btn_selected.png")}/>}
           </View>
        </Col>
   </Row>
</TouchableOpacity>
)

I wanna that when I click on any row, the toggle will be only worked on that row, other rows will not be changed. But the thing is that when I click on any row, all rows are changed. What are the solutions for this problem?

Thanks!

Your issue is you are using the same state variable selected to track the state of all components in the map.

I would try something like this (I cant test at the moment but i think you will get the idea):

toggleSelected = (index) => {
    var selected = this.state.selected
    selected[index] = !selected[index]
    this.setState({selected:selected})
  }

data.allRoomTypes.edges.map( (c, index)  =>
<TouchableOpacity key={c.node.roomTypeId} onPress={(index) => this.toggleSelected(index)}>
   <Row style={styles.boxWithShadow}>
       <Col style={{marginLeft:160}}>
          <View style={{flex:1, flexDirection:"row"}}>
             {this.state.selected[index] === false ? <Image style={styles.center} source={require("../../images/roomtypes/radio_btn_unselected.png")}/> : <Image style={styles.center} source={require("../../images/roomtypes/radio_btn_selected.png")}/>}
           </View>
        </Col>
   </Row>
</TouchableOpacity>
)

The idea being your selected state is an object {} itself with a key for every index representing the TouchableOpacity elements.

Note: The above code assumes you are initializing the selected object somewhere in your code. Like selected = {1:False, 2:True...}

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