在React中如何将表格所有勾选数据存入新数组?
实现方案
你只需要新增一个状态存储选中的学生条目,再修改复选框的事件逻辑和状态绑定即可,完整实现如下:
import { useState } from 'react'; // 学生数组实际从服务端拉取,此处为示例数据 const students = [ { _id: 1, name: "Ahmed Ali" }, { _id: 2, name: "John Doe" }, { _id: 3, name: "Jane Doe" }, { _id: 4, name: "Farah Gedi" }, { _id: 5, name: "Mustafa Jama" } ] function AttendanceTable() { // 声明状态存储选中的学生,可按需选择存完整对象或者仅id数组 const [selectedStudents, setSelectedStudents] = useState([]); const attendCheck = (e) => { const { checked, value } = e.target; const studentId = Number(value); if (checked) { // 存完整学生对象的写法,只需要id的话直接push studentId即可 const selectedStd = students.find(std => std._id === studentId); setSelectedStudents(prev => [...prev, selectedStd]); } else { // 取消勾选时过滤掉对应学生,存id的话就判断id是否相等 setSelectedStudents(prev => prev.filter(std => std._id !== studentId)); } } return ( <table className='table table-sm hover bordered striped'> <thead> <tr> <th>STD ID</th> <th>NAME</th> <th> </th> </tr> </thead> <tbody> {students && students.map((std) => ( <tr key={std._id}> <td>{std._id}</td> <td>{std.name}</td> <td> <input className='form-check-input me-1' type='checkbox' id={`${std._id}`} name={`${std.name}`} onChange={attendCheck} value={std._id} // 绑定checked属性保证视图和状态同步 checked={selectedStudents.some(item => item._id === std._id)} /> </td> </tr> ))} </tbody> </table> ) }
补充说明
- 上述代码中
selectedStudents就是你需要的已勾选条目数组,可直接在提交、统计等逻辑中使用 - 如果只需要存储选中学生的id,可按照代码注释修改状态的更新和判断逻辑,性能更优
- 原代码中STD ID列错放了学生姓名,已在示例中修正,可按需调整
内容的提问来源于stack exchange,提问作者Ahmed Ibrahim
相关产品推荐
相关产品推荐

