简体   繁体   中英

React native FlatList with Radio Button

class App extends Component {
constructor() {
    super();
    this.state = {checked: false}}
onCheck = () => {
    const { checked } = this.state;
    if(checked == true){this.setState({ checked: false  }) }
    else {this.setState({ checked: true  })}}
render() {
    return (     
            <FlatList 
                 data = {[
                    {firstName:'User_A',},
                    {firstName:'User_B',},
                    {firstName:'User_C',},
                    {firstName:'User_D',},
                    {firstName:'User_E',},
                ]}
                 renderItem = {({item}) => 
                <TouchableOpacity  onPress={() => { this.onCheck() }} activeOpacity = {0.5}>

                 <View style = {{flexDirection : 'row'}}>
                  <Left>
                 <Radio selected = {this.state.checked}/>
                 </Left>
                 <Card style = {{marginRight : 100, height : 50}}>   
        <View>
            <View>
                <Text> {item.firstName} </Text>
        </View>
                 </Card>
                 </View>
                </TouchableOpacity>
                }
                 />
    )
}

} Using react native i need a flatlist with radio button for selecting each item separately, but when i press an item every item in the list gets selected. How to manage single item selection? Above is my code and sample output

The idea here would be:

  • To create a separated component to avoid useless re-renders
  • To store the selected index in the state, and not a boolean, so that the radio button would look like

<Radio selected={this.state.selectedIndex === index}/> , where index is part of the object received by renderItem

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