React中為什麼點選一個複選框會取消先前的選擇?
<p>我有多個複選框,當我點擊一個複選框然後點擊下一個時,前一個複選框會被取消選擇,你知道為什麼嗎? </p>
<p>這是我的複選框組件:</p>
<pre class="brush:php;toolbar:false;">const Checkbox = ({ key, id, label, checked, name, onChange }:any) => {
return (
<div className="checkbox-wrapper">
<input multiple key={id} id={id} type="checkbox" checked={checked} name={name} onChange={onChange} />
<label htmlFor={id}>{label}</label>
</div>
)
}</pre>
<p>這是主要組件的樣子,數據存在一個數組中,然後被映射出來,但我不確定為什麼它會取消選擇前一個複選框,我已經刪除了很多其他無用的JSX代碼:< /p>
<pre class="brush:php;toolbar:false;">const checkboxList = [
{
id:0,
label:"大寫",
name: "upper",
checked:false
},
{
id:1,
label:"小寫",
name: "lower",
checked:false
},
{
id:2,
label:"數字",
name: "number",
checked:false
},
{
id:3,
label:"符號",
name: "symbols",
checked:false
}
]
const PasswordGenerator = () => {
const [data, setData] = useState(checkboxList)
const handleChange = (id:number) => {
const updateCheckboxes = checkboxList.map((checkbox) =>
checkbox.id === id ? {...checkbox, checked: !checkbox.checked}:checkbox)
setData(updateCheckboxes)
}
return (
<div className="elements">
{data.map((obj) => {
return(
<div key={obj.id}>
<Checkbox
multiple={true}
id={obj.id}
label = {obj.label}
checked= {obj.checked}
name= {obj.name}
onChange = {() => handleChange(obj.id)}
/>
</div>
)
})}
</div>
)
}</pre>
<p><br /></p>