我试图从所有选中的复选框中获取值并将它们存储在 useState 中。我能够获取表中选定行的值,但无法在状态中存储多个选定值。我的代码是
import React, { useState } from "react";
export default function App() {
const data = [
{
id: "1",
name: "Jane",
lastName: "Doe",
age: "25"
},
{
id: "2",
name: "James",
lastName: "Doe",
age: "40"
},
{
id: "3",
name: "Alexa",
lastName: "Doe",
age: "27"
},
{
id: "4",
name: "Jane",
lastName: "Brown",
age: "40"
}
];
const [peopleInfo, setPeopleInfo] = useState([
{
id: "",
first: "",
last: "",
age: ""
}
]);
console.log(peopleInfo);
return (
<div className="App">
<table>
<tr>
{data.map((item) => {
return (
<div
key={item.id}
style={{
display: "flex",
width: "150px"
}}
>
<input
onChange={() => {
setPeopleInfo({
id: item.id,
first: item.first,
last: item.last,
age: item.age
});
}}
value={peopleInfo}
style={{ margin: "20px" }}
type="checkbox"
/>
<td style={{ margin: "20px" }}>{item.name}</td>
<td style={{ margin: "20px" }}>{item.lastName}</td>
<td style={{ margin: "20px" }}>{item.age}</td>
</div>
);
})}
</tr>
</table>
</div>
);
}
我能够获取所选行的 ID、姓名、姓氏和年龄值,但是当我选择新复选框时,前一行的信息会更新为新的。我似乎无法弄清楚如何存储来自多个选定复选框的所有值。非常感谢任何帮助和建议。
最佳答案
可以有一个包含您选择的人的数组。
const [peopleInfo, setPeopleInfo] = useState([]);
您要做的是使用 e.target.checked
值修改上面的数组。
<input
onChange={(e) => {
// add to list
if (e.target.checked) {
setPeopleInfo([
...peopleInfo,
{
id: item.id,
first: item.name,
last: item.lastName,
age: item.age,
},
]);
} else {
// remove from list
setPeopleInfo(
peopleInfo.filter((people) => people.id !== item.id),
);
}
}}
value={peopleInfo}
style={{ margin: '20px' }}
type="checkbox"
/>
并且可以从 peopleInfo
访问结果。
关于reactjs - 如何在 React JS 中获取多个复选框的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66434403/