【发布时间】:2019-02-17 14:09:49
【问题描述】:
我正在开发一个反应组件,我有 3 个复选框。我的要求是,当检查第三个复选框时,先前检查的第一个复选框中的任何一个都应该取消选中和禁用。当第三个复选框未选中时,之前选中的任何复选框都应再次选中。
前两个复选框是从这样的数组中动态填充的:
{credits.map((section, i) => (
<p key={i}>
<input
disabled={this.state.checkedChkBox === "noneApply"}
id={`amtChk${i + 1}`}
type="checkbox"
name="amountCheck"
value={`${section.amount} - ${section.date}`}
/>
<label htmlFor={`amtChk${i + 1}`} id={`amtLbl${i + 1}`}>
{section.amount}
</label>
</p>
))}
第三个复选框看起来像这样
<input onChange={evt => this.noneApplyChk(evt)} id="noneApply" type="checkbox" name="noneApplyCheck" value="noneApply" />
<label htmlFor="noneApply" id="noneApplyLbl">
None apply
</label>
在我的构造函数中,我定义了一个状态来处理禁用前 2 个复选框。
constructor(props) {
super(props);
this.state = { checkedChkBox: "" };
}
这就是我的 noneApplyChk 函数的样子
noneApplyChk(evt) {
if (this.state.checkedChkBox === "noneApply") {
this.setState({ checkedChkBox: "" });
} else {
this.setState({ checkedChkBox: evt.target.id });
}
}
它很好地禁用/启用了前 2 个复选框,但我仍然无法找到在取消选中/选中第三个复选框时选中/取消选中前 2 个复选框的方法。我还在前 2 个复选框上尝试了 checked={this.state.checkedChkBox !== "noneApply" || this.state.checkedChkBox !== ""} 以及 onChange 事件。这也没有帮助。
如果有人有任何想法,请告诉我。
PS:我想用 react 方式而不是 jquery 方式。
【问题讨论】: