React Material UI表中的单元格引用 [英] Cell References in React Material UI Table

查看:42
本文介绍了React Material UI表中的单元格引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习React,并想制作一个可编辑的表格,其中$/Unit单元格随Price和Units单元格而变化.

I am learning React and want to make a editable table where the $/Unit cell changes with Price and Units cells.

我努力寻找一种访问其他单元格值的方法.是否可以使用Material UI表来做到这一点?

I struggle to find a way to access other cell values. Is it a possible to do it with Material UI table?

CodeSandbox: https://codesandbox.io/s/elated-meadow-486z9

CodeSandbox: 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);
          })
      }}
    />
  );
}

推荐答案

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

Inside onRowUpdate you can manipulate your newData values and then pass the modified values to setData func. A simple way to do it could be:

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".可从不",

Also if you want to restrict that field from being modified, you can set the 'editable' attribute at the column definition to 'never'. editable: "never",

链接到沙盒.

这篇关于React Material UI表中的单元格引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆