我有这个复选框组件!
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>
)
}
选中的类将显示选中标记,但是如果我要渲染多个复选框,则问题是所有复选框都被同时选中!
我只希望选中一个,而其他不选中!
答案 0 :(得分:1)
解决方案是保持选中状态的复选框,并将此状态存储在显示所有复选框的父级中
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}/>
</>
)
}