如何只选中两个复选框中的一个?

时间:2020-12-23 04:01:30

标签: reactjs

我有两个复选框,而我当时只需要其中一个为真。 因此,如果 checkbox1 为 true,则 checkbox2 应为 false。 我当前的代码仅在我使用第一个复选框时才有效,但第二个复选框的行为不正确。

这是我的复选框:

<Checkbox
 checked={checkbox1}
 onChange={onChange}
/>
<Checkbox
 checked={checkbox2}
 onChange={onChange}
/>

我的复选框组件:

<input
 type="checkbox"
 className="filled-in"
 checked={this.state.checked}
 data-cy={this.props.cyCheckbox}
/>

以及我试图操纵状态以设置 CheckBox 选中 true 或 false 的父组件:

<Access
 checkbox1={this.state.input.checkbox1}
 checkbox2={this.state.input.checkbox2}
 onChange={this.updateInput}
/>;
state = {
  input:{
   checkbox1: false,
   checkbox2: false,
  }
}
updateInput = (key, value) => {
 let { input } = this.state;
 input[key] = value;
 this.setState({ input });
 window.input = input;

 //this is where I try to set another Checkbox false if first one is true.

 if (input.checkbox1) {
 input.checkbox2= false;
 } else if (input.checkbox2) {
 input.checkbox1= false;
 } else {
 input.checkbox2= true;
 input.checkbox1= true;
 } 
}

1 个答案:

答案 0 :(得分:0)

我不能确定,因为您的示例不完整,但我认为您的问题是您的复选框代码永远无法到达 else if 子句,除非第一个复选框已取消选中。根据键和值制作条件,你会没事的。类似的东西:

if (key === 'checkbox1' && value) {
    input.checkbox1 = true;
    input.checkbox2 = false;
} else if (key === 'checkbox2' && value) {
    input.checkbox1 = false;
    input.checkbox2 = true;
}
相关问题