Material-Table 1.69.3带选择功能时行级编辑按钮显示异常求助
解决Material-Table开启选择功能后,按行数据控制编辑按钮显示的问题
针对你使用Material-Table 1.69.3版本时,开启选择功能后无法根据行数据控制编辑按钮显示的问题,可以通过自定义action的render逻辑来解决,具体实现如下:
核心思路
开启选择功能后,Material-Table对行的渲染上下文发生变化,原有的visible属性依赖rowData的判断逻辑会失效。改用render属性自定义编辑按钮的渲染逻辑,直接基于rowData判断是否显示按钮,同时阻止按钮点击触发行选择事件。
代码示例
import MaterialTable from "material-table"; import EditIcon from "@material-ui/icons/Edit"; import IconButton from "@material-ui/core/IconButton"; // ... 其他组件代码 <MaterialTable title="数据表格" columns={[ { title: "Nombre", field: "nombre" }, { title: "Apellido", field: "apellido" }, { title: "Estado", field: "estado" } // 最后一列,用于判断的字段 ]} data={[ { nombre: "Juan", apellido: "Pérez", estado: "No Informado" }, { nombre: "María", apellido: "González", estado: "Completado" }, { nombre: "Carlos", apellido: "López", estado: "No Informado" } ]} options={{ selection: true // 开启行选择功能 }} actions={[ { tooltip: "Editar fila", render: (rowData) => { // 判断最后一列值是否为"No Informado" if (rowData.estado === "No Informado") { return ( <IconButton onClick={(e) => { e.stopPropagation(); // 阻止点击按钮触发行选择 // 这里添加你的编辑逻辑 alert(`编辑行: ${rowData.nombre} ${rowData.apellido}`); }} size="small" > <EditIcon /> </IconButton> ); } return null; // 不满足条件时不渲染按钮 } } ]} />
关键说明
- 使用
render替代原有的visible属性,直接控制按钮的渲染与否,不受选择功能的影响; - 添加
e.stopPropagation()避免点击编辑按钮时触发行的选中/取消选中事件; - 确保判断逻辑中的字段名与你表格最后一列的
field属性一致。
如果上述方案仍有问题,你也可以考虑通过自定义列的方式,将编辑按钮放在最后一列单元格中,同样基于rowData控制显示,但前者更符合Material-Table的action设计规范。
内容的提问来源于stack exchange,提问作者AleOjeda
相关产品推荐
相关产品推荐

