我正在尝试在Web应用程序中添加复选框。复选框显示在网页上。我想将复选框检查值保存在本地存储中,因此我可以在页面刷新时保持复选框处于选中状态。我怎样才能做到这一点?
{
Object.keys(catagory_products).map((item, index) => {
if (item == 'brandlist') {
return catagory_products.brandlist.map((BrandList, index) =>
// console.log(BrandList)
(
<div className="custom-control custom-checkbox ml-2">
<input
type="checkbox"
className="custom-control-input checksave"
id={`${BrandList}`}
name="brand[]"
value={`${BrandList}`}
onChange={this.toggleCheckboxChange}
autoComplete="off"
/>
<label
className="custom-control-label brandname"
htmlFor={`${BrandList}`}
>
{BrandList}
I </label>
</div>
),
);
}
});
}
请帮助我该怎么做?
答案 0 :(得分:2)
请找到以下代码:
componentDidMount() {
const items = {...localStorage};
this.setState({
items,
})
}
toggleCheckboxChange = (e) => {
e.preventDefault()
if (e.target.type === 'checkbox') {
localStorage.setItem({ [e.target.id]: e.target.checked })
}
}
render() {
return(
<div>
{
Object.keys(catagory_products).map((item, index) => {
if (item === 'brandlist') {
return catagory_products.brandlist.map((BrandList, index) =>
// console.log(BrandList)
(
<div className="custom-control custom-checkbox ml-2">
<input
type="checkbox"
className="custom-control-input checksave"
id={BrandList.id}
name="brand[]"
value={!!this.state[BrandList.id]}
onChange={this.toggleCheckboxChange}
autoComplete="off"
/>
<label
className="custom-control-label brandname"
htmlFor={BrandList}
>
{BrandList}
I </label>
</div>
),
);
}
});
}
</div>
)}