簡體   English   中英

用單選按鈕反應本地FlatList

[英]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>
                }
                 />
    )
}

}使用react native時,我需要一個帶有單選按鈕的flatlist來分別選擇每個項目,但是當我按下一個項目時,列表中的每個項目都會被選中。 如何管理單項選擇? 上面是我的代碼和示例輸出

這里的想法是:

  • 創建分離的組件以避免無用的重新渲染
  • 將所選索引存儲在狀態中,而不是布爾值中,以便單選按鈕看起來像

<Radio selected={this.state.selectedIndex === index}/> ,其中index是renderItem接收的對象的一部分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM