React与Material UI表格添加删除列问题
实现Material UI表格右侧新增删除列的方法
当然可以在表格右侧新增删除列,只需调整表格行结构并添加删除按钮逻辑即可,具体修改如下:
关键修改点
- 在第一组
<TableRow>中新增一个<TableCell>用于放置删除按钮 - 将第二组
<TableRow>中<TableCell>的colSpan属性从2改为3,使其覆盖原有的数据列,保持布局一致 - 启用删除按钮的点击事件,通过
arrayHelpers.remove(index)实现对应行的删除逻辑
修改后的完整代码
import RemoveCircleOutlineIcon from '@mui/icons-material/RemoveCircleOutline'; // 确保已导入该图标 const CustomTableRow = ({ row, index, arrayHelpers }) => { return ( <> <TableRow sx={{ "th, td": { border: 0 } }} > <TableCell component="th" scope="row"> <FastField name={`rows.${index}.attribute`} component={TextField} fullWidth /> </TableCell> <TableCell> <FastField name={`rows.${index}.ruleId`} component={TextField} fullWidth /> </TableCell> {/* 新增的删除按钮列 */} <TableCell align="right"> <IconButton aria-label="delete" onClick={() => arrayHelpers.remove(index)} size="small" > <RemoveCircleOutlineIcon sx={{ fontSize: "1.25rem" }} /> </IconButton> </TableCell> </TableRow> <TableRow> {/* 调整colSpan为3,覆盖所有数据列 */} <TableCell colSpan={3}> <FastField name={`rows.${index}.thirdRow`} component={TextField} fullWidth /> </TableCell> </TableRow> </> ); };
说明
- 删除按钮的点击事件通过
arrayHelpers.remove(index)直接调用表单数组的删除方法,确保删除后表单数据同步更新 - 调整
colSpan是为了让第二行的输入框依然占据原有数据列的宽度,避免布局错乱 - 需确保已正确导入
RemoveCircleOutlineIcon图标组件,否则按钮无法正常显示
内容的提问来源于stack exchange,提问作者Joseph
相关产品推荐
相关产品推荐

