首页 > 解决方案 > 如何处理循环中的复选框反应原生

问题描述

如何在本机反应中处理循环内的复选框。目前,我的代码是这样的。

this.state.allItems.map((res, index) => {
 return(
     <CheckBox 
         color="green"
         style={{ marginRight: 20, }}
         checked={this.state.check1}
         onChange={()=>{ }}
/>

)

})

标签: reactjsreact-native

解决方案


如果我正确理解您的问题,则您有多个项目,并且您希望它们可以独立检查。

为此,您需要让它们每个都有自己的状态值。你如何做到这一点取决于你的设计需求,但形成你的代码你需要一个数组而不是 check1 状态。

像这样的东西:

this.state.allItems.map((res, index) => {
 return(
     <CheckBox 
         color="green"
         style={{ marginRight: 20, }}
         checked={this.state.checked[index]}
         onChange={()=> {
                  let { checked } = this.state;
                  checked[index] = !checked[index];
                  this.setState({checked});
         }
 }
/>

当然,您需要使用数组正确填充检查状态。


推荐阅读