【问题标题】:React native FlatList with Radio Button使用单选按钮反应原生 FlatList
【发布时间】:2018-08-05 20:13:12
【问题描述】:
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


    【解决方案1】:

    这里的想法是:

    • 创建一个分离的组件以避免无用的重新渲染
    • 将选定的索引存储在状态中,而不是布尔值,以便单选按钮看起来像

    &lt;Radio selected={this.state.selectedIndex === index}/&gt;,其中 index 是 renderItem 接收到的对象的一部分

    【讨论】:

    • 我试过了,但没有改变,所有的项目都会在选择一个项目时被选中。
    • @Malini 您可以创建自己的单选按钮组件并将其添加到您的平面列表中。例如 &lt;MyRadio /&gt; 并通过更改 &lt;MyRadio /&gt; 组件中的状态将其更改为 focus
    • @Harrison 你能分享一个示例编码吗?
    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2018-04-17
    • 1970-01-01
    相关资源
    最近更新 更多