【问题标题】:Cell References in React Material UI TableReact Material UI 表中的单元格引用
【发布时间】:2020-06-13 21:06:44
【问题描述】:

我正在学习 React,并希望制作一个可编辑的表格,其中 $/Unit 单元格随价格和单位单元格而变化。

我很难找到访问其他单元格值的方法。是否可以使用 Material UI 表来做到这一点?

代码沙盒:https://codesandbox.io/s/elated-meadow-486z9

import React from "react";
import MaterialTable from "material-table";

export default function CustomEditComponent(props) {
  const { useState } = React;

  const [columns, setColumns] = useState([
    {
      title: "Product",
      field: "product"
    },
    {
      title: "Price",
      field: "price"
    },
    {
      title: "Units",
      field: "pack"
    },
    {
      title: "$/Unit",
      field: "unitPrice",
      editComponent: props => (
        <input
          type="number"
          value={props.value} //how to access other cell values?
          onChange={e => props.onChange(e.target.value)}
        />
      )
    }
  ]);

  const [data, setData] = useState([
    { product: "Coke", price: 12, pack: 12, unitPrice: 1 },
    { product: "Beer", price: 12, pack: 6, unitPrice: 2 }
  ]);

  return (
    <MaterialTable
      title="Custom Edit Component Preview"
      columns={columns}
      data={data}
      editable={{
        onRowUpdate: (newData, oldData) =>
          new Promise((resolve, reject) => {
            setTimeout(() => {
              const dataUpdate = [...data];
              const index = oldData.tableData.id;
              dataUpdate[index] = newData;
              setData([...dataUpdate]);

              resolve();
            }, 1000);
          })
      }}
    />
  );
}

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    在 onRowUpdate 中,您可以操作 newData 值,然后将修改后的值传递给 setData 函数。一个简单的方法可能是:

    onRowUpdate: (newData, oldData) =>
          new Promise((resolve, reject) => {
            setTimeout(() => {
              const dataUpdate = [...data];
              const index = oldData.tableData.id;
              newData["unitPrice"] = newData["price"] / newData["pack"];
              dataUpdate[index] = newData;
              setData([...dataUpdate]);
    
              resolve();
            }, 1000);
          })
    

    此外,如果您想限制该字段被修改,您可以将列定义中的“可编辑”属性设置为“从不”。 editable: "never",

    链接到sandbox

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 2018-01-13
      相关资源
      最近更新 更多