问题
I am learning React and want to make a editable table where the $/Unit cell changes with Price and Units cells.
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
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);
})
}}
/>
);
}
回答1:
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);
})
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",
Link to sandbox.
来源:https://stackoverflow.com/questions/62365559/cell-references-in-react-material-ui-table