【发布时间】:2019-08-05 05:12:48
【问题描述】:
我有一个映射函数,它将 JSON 值显示为复选框,每个复选框触发另外 2 个复选框,我使用的 JSON 有一个最小值/最大值,我创建了一个函数来设置每个部分中复选框选择的最小值/最大值,这两个功能都可以正常工作。但是,问题是,一旦单击父复选框并展开以显示 2 个功能复选框,然后我重做单击它以缩小它并再次单击它以展开它的过程,子复选框将不再可单击。
复选框值作为道具从 Checkbox.js 传递到发生 fetch/map 的 Itemlist.js。如果有人能解释或演示如何实现这一点,将不胜感激。
React 实时片段:https://codesandbox.io/embed/oo059p7q19?fontsize=14
Checkbox.js
import React from "react";
import "./Checkbox.css";
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;
【问题讨论】:
标签: javascript reactjs checkbox ecmascript-6 mapping