[英]How can I determine which checkbox is checked?
<table>
<tbody>
<tr>
<th>Select</th>
<th>User Id</th>
<th>Id</th>
<th>Is Banned?</th>
<th>registration_date</th>
</tr>
{data.map((item, i) => (
<tr key={i}>
<td><input type="checkbox" checked={isChecked} /></td>
<td>{item.user_id}</td>
<td>{item.user_name}</td>
<td className="isbanned">{item.isbanned}</td>
<td>{item.registration_date}</td>
</tr>
))}
</tbody></table>
this is my code as you see in up.这是我在上面看到的代码。 My question is:我的问题是:
How can I detect user_id 1 checbox is checked?如何检测 user_id 1 复选框被选中?
How should I change my code?我应该如何更改我的代码? or what I can use for that?或者我能用什么?
You can do something like this你可以做这样的事情
const data = [
{
user_id: "some-id",
user_name: "Me",
isbanned: "no",
registration_date: "2000",
},
]
function StackOverflow() {
const [selectedUserIds, setSelectedUserIds] = useState([])
const addOrRemoveId = (id) => {
setSelectedUserIds((state) => {
if (state.includes(id)) {
// If new id exists in current list then we remove it from state
return selectedUserIds.filter((currentId) => currentId !== id)
}
// Else we add the item id to our state
return [...state, id]
})
}
return (
<table>
<tbody>
<tr>
<th>Select</th>
<th>User Id</th>
<th>Id</th>
<th>Is Banned?</th>
<th>registration_date</th>
</tr>
{data.map(({ user_id, ...item }) => (
<tr key={user_id}>
<td>
<input
checked={selectedUserIds.includes(user_id)}
onChange={() => addOrRemoveId(user_id)}
type="checkbox"
/>
</td>
<td>{user_id}</td>
<td>{item.user_name}</td>
<td className="isbanned">{item.isbanned}</td>
<td>{item.registration_date}</td>
</tr>
))}
</tbody>
</table>
)
}
To consider: Never use an index or a combination string of them as component keys.考虑:永远不要使用索引或它们的组合字符串作为组件键。 Keys are intended to be unique, if you have an userId already, then use it as that key id键是唯一的,如果您已经有一个 userId,则将其用作该键 id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.