在React Native中使用多个复选框处理状态

瓦斯瓦·塞缪尔(Wasswa Samuel)

我有两个复选框一个简单的表格有人来选择一种或另一种,即YesNo不能同时使用。我正在使用React-native-element工具包,如下所示。

export default class CheckerForm extends React.Component {
     state = {
       checked: false,
      }
    handleYesCheck =() => {
       this.setState({checked: !this.state.checked})
    }

    handleNoCheck =() => {
      this.setState({checked: !this.state.checked})
    }

    render(){

   const { checked } = this.state
     return (
      <View>
       <CheckBox
       center
        title='Yes'
        checked={checked}
        onPress={this.handleYesCheck}
     />
     <CheckBox
      center
      title='No'
      checked={checked}
      onPress={this.handleNoCheck}
    />
   <View>

我想捕获并修改复选框的状态,但是当我单击其中一个复选框时,我修改了另一个的状态,即,将同时选中和取消选中这两个复选框。如何修改复选框的状态独立,这样当我点击YesNo没有被选中,反之亦然?通常,什么是捕获状态的最佳方法,以便我可以使用它。

文科夫斯基

您可以做的是拥有一个复选框数组,并将选中的索引保存在状态中。

 state = {
   checkedId: -1,
   checkboxes: [{id: "yes", title: "Yes"}, {id: "no", title: "No"}]
 }

 handleCheck = (checkedId) => {
   this.setState({checkedId})
 }

 render() {
   const { checkboxes, checkedId } = this.state
   return (
     <View>
       {checkboxes.map(checkbox => (
         <CheckBox
           center
           key={checkbox.id}
           title={checkbox.title}
           checked={checkbox.id == checkedId}
           onPress={() => this.handleCheck(checkbox.id)}
         />
       )}
     <View>
   )
 }

这样,您还可以处理两个以上的复选框,并且还知道其中一个由索引选中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章