[英]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>
這是我在上面看到的代碼。 我的問題是:
如何檢測 user_id 1 復選框被選中?
我應該如何更改我的代碼? 或者我能用什么?
你可以做這樣的事情
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>
)
}
考慮:永遠不要使用索引或它們的組合字符串作為組件鍵。 鍵是唯一的,如果您已經有一個 userId,則將其用作該鍵 id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.