在您的样例代码中,您没有设置checked
值,我假设您有一个searchPropRef
布尔值.如果你要用checked
,你应该用onChange
而不是onClick
.如果页面上有number of checkboxes,请确保它们都使用唯一的ID、名称和州值.
下面是一个带有两个复选框的工作示例:https://stackblitz.com/edit/stackblitz-starters-tfjeiz?file=src%2FApp.js
const [searchPropRef1, setSearchPropRef1] = useState(false);
const [searchPropRef2, setSearchPropRef2] = useState(false);
const handleSearchPropRef1 = (e) => {
const value = e.target.checked;
setSearchPropRef1(value);
};
const handleSearchPropRef2 = (e) => {
const value = e.target.checked;
setSearchPropRef2(value);
};
return (
<div>
<div>
<input
type="checkbox"
id="search1"
name="search1"
checked={searchPropRef1}
onChange={handleSearchPropRef1}
/>
<label htmlFor="search1">Search1</label>
</div>
<div>
<input
type="checkbox"
id="search2"
name="search2"
checked={searchPropRef2}
onChange={handleSearchPropRef2}
/>
<label htmlFor="search2">Search2</label>
</div>
</div>
);
您应该不需要任何回调来使某些复选框起作用.