在 MUI 数据网格中动态更改单元格值

Change cell value dynamically in MUI Data Grid

在我的数据网格中,我有 9 列,您可以在其中看到名为 RateTransfer 的两列。我还有一个名为 Total 的列,我想在其中显示 RateTransfer 的乘法结果以及 Transfer 单元格值的变化。 请注意 我已将 Transfer 列设置为可编辑,以便 Total 列的值随传输值而变化。在 DataGrid 中有一个名为 onCellFocusOut() 的道具,它会在您单击单元格外部后为您提供单元格值。但这并没有给你更新的价值。我尝试使用 useEffect()useState() 设置 Transfer 单元格的值并相应地更新 Total 。但它没有用。希望我已经清楚地解释了我想在这里实现的目标。

我的代码

const Transition = React.forwardRef(function Transition(props, ref) {
  return <Slide direction="left" ref={ref} {...props} />;
});

function FullScreenDialog({ open, handleClose }) {
  const columns = [
    {
      field: "Lot",
      headerName: "Lot#",
      width: 200,
      editable: false,
    },
    { field: "Bill", headerName: "Bill#", width: 130, editable: false },
    {
      field: "Shelf",
      headerName: "Shelf",
      width: 200,
      editable: false,
    },
    {
      field: "Bin",
      headerName: "Bin",
      width: 200,
      editable: false,
    },
    {
      field: "Rate",
      headerName: "Rate",
      width: 200,
      editable: false,
    },
    {
      field: "Stock",
      headerName: "Stock Balance Qty.",
      width: 200,
      editable: false,
    },
    {
      field: "Transfer",
      headerName: "Transfer Qty.",
      width: 200,
      editable: true,
    },
    {
      field: "Total",
      headerName: "Total",
      width: 200,
      editable: false,
    },
  ];

  // React.useEffect(() => {
  //   setTotal(rate * transfer);
  //   console.log("total", total);
  // }, [transfer]);

  const [transferCellValue, setTransferCellValue] = React.useState(null);
  const [total, setTotal] = React.useState(1);
  console.log("transfer cell value", transferCellValue);
  const defaultRows = [
    {
      id: 1,
      Lot: "2101000134",
      Bill: "M0000013092",
      Shelf: "W13-A1",
      Bin: "B01",
      Rate: 221,
      Stock: 128.0,
      Transfer: 12,
      Total: total,
    },
  ];

  // console.log(transferCellValue);

  return (
    <div>
      <Dialog
        fullScreen
        open={open}
        onClose={handleClose}
        TransitionComponent={Transition}
      >
        <div style={{ height: 400, width: "100%" }}>
          <DataGrid
            rows={defaultRows}
            columns={columns}
            onCellFocusOut={(e) => console.log(e.value)}
          />
        </div>
      </Dialog>
    </div>
  );
}

如果你只是想通过Transfer * Rate来计算总列,你可以使用valueGetter到return一个动态值。

valueGetter: Function that allows to get a specific data instead of field to render in the cell.

{
  field: "Total",
  headerName: "Total",
  width: 200,
  valueGetter: (params) => params.row.Transfer * params.row.Rate
}

https://codesandbox.io/s/mui-datagrid-dynamic-column-tdod5