You are passing the input
tag checked
value with one state boolean variable.
Make checked
state as an array and indicate it using index
for input tag.
On handleCheck()
method, update the corresponding index item of the state.
import { useState } from "react";
import "./styles.css";
export default function App() {
const [allchecked, setAllchecked] = useState(false);
const [checked, setChecked] = useState([false, false, false]);
const names = ["John", "Doe", "Jim"];
const handleCheck = (event, index) => {
const _checked = [...checked];
_checked[index] = event.target.checked;
setChecked(_checked);
};
const selectAll = (event) => {
setAllchecked(event.target.checked);
const isChecked = event.target.checked;
console.log(isChecked);
setChecked([isChecked, isChecked, isChecked]);
};
return (
<div className="App">
<input type="checkbox" checked={allchecked} onChange={selectAll} />
Select All
{names.map((values, index) => (
<div>
<input
type="checkbox"
checked={checked[index]}
onChange={(event) => handleCheck(event, index)}
/>
{values}
</div>
))}
</div>
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…