【发布时间】:2020-03-24 01:21:42
【问题描述】:
我有多个动态复选框。这些复选框被放置(假设)在“B”组件中。 我已经在“B”的父级“A”组件中管理了这些复选框的状态。 当一个或所有复选框被点击时,我想渲染一个 div
预期结果:如果单击一个或所有复选框,则呈现 div。如果没有选择,则应该隐藏 div。基本上,即使选中了一个复选框,div 也应该是可见的。
当前结果:当点击一个复选框时,会呈现 div,但如果选中另一个复选框,则 div 会消失。
这是我的 A 组件(父级)
const A = () => {
const [isChecked, setIsChecked] = useState(false) // state that holds state of check boxes
return (
{isChecked ? <div>Some Content..</div> : null} // rendering the div according to the state of the checkboxes
<Child isChecked={isChecked} setIsChecked={setIsChecked} />
)
}
子组件代码
const Child = props => {
return (
{checkBoxList.map((box, index) => (
<CustomCheckBox
key={index}
name={`check-box-${index}`} // to uniquely identify each check box
isChecked={props.isChecked}
setIsChecked={props.setIsChecked} />
))}
)
}
CustomCheckBox 组件:
const CustomCheckBox = props => {
const onChangeHandler = (event) => {
props.isChecked ? props.setIsChecked(false) : props.setIsChecked(true)
}
return <input name={props.name} type="checkBox" onChange={onChangeHandler} />;
};
CustomCheckBox.propTypes = {
name: string
}
我知道父组件状态现在只能处理一个复选框。
当前结果的原因是因为我在onChangeHandler函数中包含的条件。
props.isChecked ? props.setIsChecked(false) : props.setIsChecked(true)
我对如何在上述场景中使用单个处理函数处理多个复选框的状态感到困惑!
【问题讨论】:
标签: reactjs checkbox react-props react-component conditional-rendering