javascript - 复选框限制功能发生后复选框变得不可点击reactjs
问题描述
我有一个映射函数,它将 JSON 值显示为复选框,每个复选框触发另外 2 个复选框,我使用的 JSON 有一个最小值/最大值,我创建了一个函数来设置每个部分中复选框选择的最小值/最大值。我的问题是,一旦单击父和子复选框,然后我重做单击它以缩小它并再次单击它以展开它的过程,子复选框将不再可单击。
复选框值作为道具从Checkbox.js传递到Itemlist.js发生提取/映射的地方。
React 实时片段:https ://codesandbox.io/embed/2178pwz6or?fontsize=14
复选框.js
class Checkboxes extends React.Component {
constructor(props) {
super(props);
this.state = {
currentData: 0,
limit: 2,
checked: false
};
}
selectData(id, event) {
let isSelected = event.currentTarget.checked;
if (isSelected) {
if (this.state.currentData < this.props.max) {
this.setState({ currentData: this.state.currentData + 1 });
} else {
event.preventDefault();
event.currentTarget.checked = false;
}
} else {
if (this.state.currentData > this.props.min) {
this.setState({ currentData: this.state.currentData - 1 });
} else {
event.preventDefault();
event.currentTarget.checked = true;
}
}
}
render() {
const input2Checkboxes =
this.props.options &&
this.props.options.map(item => {
return (
<div className="inputGroup2">
{" "}
<div className="inputGroup">
<input
id={this.props.childk + (item.name || item.description)}
name="checkbox"
type="checkbox"
onChange={this.selectData.bind(
this,
this.props.childk + (item.name || item.description)
)}
/>
<label
htmlFor={this.props.childk + (item.name || item.description)}
>
{item.name || item.description}{" "}
{/** <img src={this.props.img} alt="" /> <span className="pricemod">{props.childprice} SAR</span>
*/}
</label>
</div>
</div>
);
});
return (
<form className="form">
<div>
{/** <h2>{this.props.title}</h2>*/}
<div className="inputGroup">
<input
id={this.props.childk + this.props.name}
name="checkbox"
type="checkbox"
checked={this.state.checked}
onChange={this.selectData.bind(
this,
this.props.childk + this.props.uniq
)}
onChange={() => {
this.setState({ checked: !this.state.checked });
}}
/>
<label htmlFor={this.props.childk + this.props.name}>
{this.props.name}{" "}
</label>
</div>{" "}
{this.state.checked ? input2Checkboxes : undefined}
</div>
</form>
);
}
}
export default Checkboxes;
解决方案
在您的代码沙箱片段中,只需将 Checkbox.js 组件中的第 24 行更改为此
if (this.state.currentData >= this.props.min) {
推荐阅读
- c - C - 数组放入变量时从同一元素返回不同的值
- python - 将 RGBA 字节数组转换为 cv2 图像(没有错误,cv2 永远挂起)
- c++ - 如何使用主要参数添加更多堆栈?
- php - PHP Decimal128 字符串格式化
- ios - 打印语句总是崩溃
- azure-devops - 如何从 Azure DevOps 在 Microsoft AppCenter 中运行 XCUITests
- javascript - 如何延迟请求数据?
- python - pandas 中的高效 STAR 选择
- python - “int”类型的参数是不可迭代的问题
- javascript - 使用 Google App Script 替换 Google Sheet 中的文本而不重新格式化值