我有这个复选框组件!
const CheckBox = props =>{
var [show,setshow] = useState(false);
const option = props.name.replace(/s/g, '');
return(
<div className="filter-option" onClick={e=>setshow(!show)} data={option}>
<div className={show?"check-bock checked":"check-bock"} >
<i className="fa fa-check"></i>
</div>
<label className="font-20">{props.name}</label>
</div>
)
}
选中的类将显示复选标记,但如果我想渲染多个复选框,问题是所有复选框都被一次选中!
我只想选中一个,而其他未选中!
解决方案是保持选中哪个复选框的状态,并将此状态存储在呈现所有复选框的父级中
const CheckBox = props =>{
const option = props.name.replace(/s/g, '');
return(
<div className="filter-option" onClick={e=>props.setshow(prev => props.name == prev? '': props.name)} data={option}>
<div className={props.show?"check-bock checked":"check-bock"} >
<i className="fa fa-check"></i>
</div>
<label className="font-20">{props.name}</label>
</div>
)
}
const Parent = () => {
var [show,setshow] = useState('');
return (
<>
<Checkbox name="first" show={"first" === show} setShow={setShow}/>
<Checkbox name="second" show={"second" === show} setShow={setShow}/>
</>
)
}