如何在Material UI表格中为每行添加自增序号列
解决方案
要实现表格#列显示从1开始的自增序号,只需对代码做两处关键修改:
1. 调整列配置
将#列的id改为自定义标识(比如"serial"),因为这一列不需要从MongoDB数据中取值:
const columns = [ { id: "serial", name: "#" }, // 替换原_id为serial { id: "name", name: "Nama" }, { id: "date", name: "Tanggal" }, { id: "phone", name: "No Telp." }, { id: "terapist", name: "Terapis" }, { id: "statust", name: "Status" }, ];
2. 渲染单元格时判断列类型
在渲染TableCell时,判断当前列是否为序号列,若是则返回索引+1(从1开始计数),否则正常读取数据。同时优化key值保证唯一性:
{columns && columns.map((column) => { let value; if (column.id === "serial") { value = i + 1; // 索引从0开始,加1得到自增序号 } else { value = row[column.id]; } // 用row._id和column.id组合作为key,避免重复 return <TableCell key={`${row._id}-${column.id}`}>{value}</TableCell>; })}
修改后的完整代码
async function getAppointment() { const res = await fetch("http://localhost:3000/api/appointment", { method: "GET", cache: "no-store", }); return res.json(); } async function Appointment() { const { appointment } = await getAppointment(); const columns = [ { id: "serial", name: "#" }, { id: "name", name: "Nama" }, { id: "date", name: "Tanggal" }, { id: "phone", name: "No Telp." }, { id: "terapist", name: "Terapis" }, { id: "statust", name: "Status" }, ]; return ( <div> <TableContainer> <Table> <TableHead> <TableRow> {columns.map((column) => ( <TableCell key={column.id}>{column.name}</TableCell> ))} </TableRow> </TableHead> <TableBody> {appointment && appointment.map((row, i) => { return ( <TableRow key={row._id}> {/* 用MongoDB的_id作为行key更稳定 */} {columns && columns.map((column) => { let value; if (column.id === "serial") { value = i + 1; } else { value = row[column.id]; } return <TableCell key={`${row._id}-${column.id}`}>{value}</TableCell>; })} </TableRow> ); })} </TableBody> </Table> </TableContainer> </div> ); } export default Appointment;
额外优化:将行的key从索引i替换为MongoDB的row._id,避免数据更新时因索引变化导致的组件渲染异常。
内容的提问来源于stack exchange,提问作者eko pram
相关产品推荐
相关产品推荐

