使用MUI DataGrid,如何在Change时更新单元格状态?

问题描述 投票:0回答:1

我需要什么:我正在使用 MUI DataGrid > 5。我需要单元格中填充的数据自动更改状态(

onChange
)。此时,我有一个
useEffect
正在监听这些更改以“启用/禁用”“保存”和“取消”按钮。

我尝试过的:使用

onCellEditCommit
属性,仅当我在 DataGrid 组件外部单击时(或者当我按 Tab 或 Enter 时),它才会保存单元格内容。我想保存单元格更改时的内容。

...
import {
  DataGrid,
  GridColDef,
  GridPreProcessEditCellProps,
  GridRowId,
} from "@mui/x-data-grid";
...

const [devices, setDevices] = useState<Device[]>(formValues.devices);

const columns: GridColDef[] = [
    {
      field: "id",
      headerName: "ID",
      flex: 10,
    },
    {
      field: "uniqueIdentification",
      headerName: "Unique ID",
      editable: true,
      flex: 30,
    },
    {
      field: "description",
      headerName: "Description",
      editable: true,
      flex: 50,
    },
    {
      field: "isActive",
      headerName: "Active",
      type: "boolean",
      editable: true,
      flex: 10,
    },
    {
      field: "actions",
      type: "actions",
      headerName: "Actions",
      width: 100,
      cellClassName: "actions",
      renderCell: (params) => (
        <Box id={`${params.id}`} component="div">
          <IconButton
            title="Remove"
            onClick={() => deleteRow(params.id)}
            size="small"
          >
            <DeleteIcon />
          </IconButton>
        </Box>
      ),
    },
  ];

  function saveDeviceCell(params) {
    const oldDevices = [...devices];

    const rowDeviceIndex = oldDevices.findIndex((dev) => dev.id === params.id);

    oldDevices[rowDeviceIndex] = {
      ...oldDevices[rowDeviceIndex],
      [params.field]: params.value,
    };

    setDevices(oldDevices);
  }

...
return (
  <DataGrid
     rows={devices}
     columns={columns}
     hideFooterPagination
     hideFooter
     disableSelectionOnClick
     autoHeight
     onCellEditCommit={saveDeviceCell}
     editMode="cell"
  />
...
);
reactjs typescript material-ui datagrid
1个回答
0
投票

我怀疑使用

processRowUpdate
来做这样的事情可能不是预期用途,但据我测试过,它对我有用。

在行和单元格编辑中使用新值更新行之前调用的回调。

类型:函数 签名: 函数(newRow:R,oldRow:R)=>承诺| R

  • newRow 具有新值的 Row 对象。
  • oldRow 具有旧值的 Row 对象。

返回:更新行的最终值。

function MyGrid() {
  // ... Ommitting not important parts
  const [rows, setRows] = useState([]);
  const handleProcessRowUpdate = (updatedRow, originalRow) => {
    const newRows = [...rows];
    const idx = newRows.findIndex((x) => x.id === originalRow.id);

    newRows[idx] = updatedRow;
    setRows(newRows);
  
    return updatedRow;
  };

  <DataGrid
    rows={rows}
    columns={columns}
    processRowUpdate={handleProcessRowUpdate}
    onProcessRowUpdateError={(params) => { // shouldn't be necessary, but just in case
      console.error(params);
    }}
  />
}
© www.soinside.com 2019 - 2024. All rights reserved.