如何解决如何使用React Hook处理多个复选框
我需要使用React中的钩子来控制所有复选框
父代码
const Filter = () => {
const [isChecked,setIsChecked] = useState({
all: false,without: false,one: false,two: false,three: false,})
const handleChange = ({ target : { name,checked } }) => {
setIsChecked({
...isChecked,[name]: checked
})
}
const checkboxes = [
{
key: "all",name: "all",htmlFor: "all",label: "Все"
},{
key: "without",name: "without",htmlFor: "without",label: "Без пересадок"
},{
key: "one",name: "one",htmlFor: "one",label: "1 пересадка"
},{
key: "two",name: "two",htmlFor: "two",label: "2 пересадки"
},{
key: "three",name: "three",htmlFor: "three",label: "3 пересадки"
},];
return (
<div className="content__filter">
<div className="content__filter__name">
Количество пересадок
</div>
<div className="content__filter__list">
<ul>
{checkboxes.map(item => (
<ListItem
key={item.key}
name={item.name}
htmlFor={item.htmlFor}
label={item.label}
checked={isChecked[item.name]}
onChange={handleChange}
/>
))}
</ul>
</div>
</div>
);
};
export default Filter;
儿童代码
const ListItem = ({ type = "checkbox",name,htmlFor,label,onChange,checked }) => {
console.log(checked)
return (
<li>
<input type={type} name={name} checked={checked} onChange={onChange}/>
<label htmlFor={htmlFor}>{label}</label>
</li>
)
};
export default ListItem;
复选框完全不起作用。我的意思是,如果单击,则什么也不会发生。我一直在孩子身上得到虚假的财产,并且无法切换。如果我将isChecked
设置为空对象(例如在此示例https://codesandbox.io/s/react-hooks-usestate-xzvq5?file=/src/index.js:380-382中),那也行不通。我在做什么错?任何帮助表示赞赏
P.s。复选框的CSS
li {
display: flex;
align-items: center;
height: 40px;
&:hover {
background: #F1FCFF;
cursor: pointer;
}
input {
display: none;
}
label {
font-family: 'Open Sans';
font-weight: 400;
font-size: 13px;
color: #4A4A4A;
cursor: pointer;
}
input + label {
display: inline-flex;
align-items: center;
user-select: none;
}
input + label::before {
content: '';
display: inline-block;
width: 20px;
height: 20px;
flex-shrink: 0;
flex-grow: 0;
border: 1px solid #9ABBCE;
border-radius: 2px;
margin-right: 10px;
background-repeat: no-repeat;
background-position: center center;
}
input:checked + label::before {
border-color: #2196F3;
background-image: url("../../img/shape.png");
}
}
解决方法
好,问题解决了。都是关于CSS的。我正在将htmlFor
的{{1}}属性传递给ListItem,而不是id。因此,我需要在item.name
数组中创建一个id属性,并像这样checkboxes
htmlFor
属性
别忘了将htmlFor={item.id}
属性和id
一样传递给ListItem
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。