如果复选框的标签为“无首选项”,如何取消选中所有其他复选框?

时间:2018-12-27 07:53:51

标签: react-native

如果在react-native中选中了特定复选框,如何取消选中所有其他复选框

这是我的代码:

 constructor(props, context) {
super(props, context);
console.log('custom/ccheckbox/index.js constructor()');
this.state = {
  checked: false,
};
}
handleCheck() {
this.setState({checked: !this.state.checked});
}

render() {

return (
  <CheckBox
    iconType='material'
    checkedIcon='check'
    uncheckedIcon='check-box-outline-blank'
    checkedColor={Colors.ORANGE}
    checked={this.state.checked}
    containerStyle={style.content}
    onPress={() => this.handleCheck()}

  />
);
}
}

如果要进行句柄检查,我该如何使用?

2 个答案:

答案 0 :(得分:0)

我不知道您有多少输入,但是您可以执行以下操作。

constructor(props, context) {
super(props, context);
console.log('custom/ccheckbox/index.js constructor()');
this.state = {
    checked: "none",
};
}
handleCheck(checked) {
  this.setState({ checked});
}

render() {
return (
    <React.Fragment>
    <CheckBox
        iconType='material'
        checkedIcon='check'
        uncheckedIcon='check-box-outline-blank'
        checkedColor={Colors.ORANGE}
        checked={this.state.checked === "first"}
        containerStyle={style.content}
        onPress={() => this.handleCheck("first")}

    />
    <CheckBox
        iconType='material'
        checkedIcon='check'
        uncheckedIcon='check-box-outline-blank'
        checkedColor={Colors.ORANGE}
        checked={this.state.checked === "second"}
        containerStyle={style.content}
        onPress={() => this.handleCheck("second")}

    />
    <CheckBox
        iconType='material'
        checkedIcon='check'
        uncheckedIcon='check-box-outline-blank'
        checkedColor={Colors.ORANGE}
        checked={this.state.checked === "third"}
        containerStyle={style.content}
        onPress={() => this.handleCheck("third")}

    />
    <CheckBox
        iconType='material'
        checkedIcon='check'
        uncheckedIcon='check-box-outline-blank'
        checkedColor={Colors.ORANGE}
        checked={this.state.checked === "fourth"}
        containerStyle={style.content}
        onPress={() => this.handleCheck("fourth")}

    />
    </React.Fragment>
);

} }

答案 1 :(得分:0)

您可以将所有检查状态存储在一个对象中:

state = { checked: {} }

  <CheckBox 
    checked={this.state.checked.chk1 } 
    onPress={() => this.setState(({ checked }) => ({ 
      checked: {...checked, chk1: !checked.chk1 } // toggle this checkbox
    }))} 
  />

  <CheckBox 
    checked={this.state.checked.chk2 } 
    onPress={() => this.setState(({ checked }) => ({ 
      checked: { chk2: !checked.chk2 } // clears other checkboxes
    }))} 
  />