如何添加 MUI DataGrid 编辑/删除按钮

Pus*_*soy 2 datagrid reactjs material-ui

我很难在 DataGrid 组件中的每行添加自定义按钮。

这是我的代码:

const columns = [
    { field: 'model_id', headerName: 'ID', width: 70, sortable: false },
    { field: 'model_code', headerName: 'Model Code', width: 130 },
    { field: 'model_description', headerName: 'Description', width: 400 },
    { field: 'actions', headerName: 'Actions', width: 400 }
];
Run Code Online (Sandbox Code Playgroud)

数据网格:

<DataGrid
rows={models}
columns={columns}
getRowId={(row) => row.model_id}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection />
Run Code Online (Sandbox Code Playgroud)

我每行想要什么: 在此输入图像描述

Ahm*_*ınç 8

您可以在列定义数组中使用renderCell函数,如下所示:

const onButtonClick = (e, row) => {
    e.stopPropagation();
    //do whatever you want with the row
};

const columns = [
    { field: 'model_id', headerName: 'ID', width: 70, sortable: false },
    { field: 'model_code', headerName: 'Model Code', width: 130 },
    { field: 'model_description', headerName: 'Description', width: 400 },
    { field: 'actions', headerName: 'Actions', width: 400, renderCell: (params) => {
        return (
          <Button
            onClick={(e) => onButtonClick(e, params.row)}
            variant="contained"
          >
            Delete
          </Button>
        );
      } }
];
Run Code Online (Sandbox Code Playgroud)

您可以查看此 stackblitz,了解该解决方案的实时工作示例。