我试图从材料 UI 创建一个数据表,但它只在“DT_RowId”字段上给我以下错误,尽管 id 是唯一的。如果我只有“id”,那么它工作正常。 任何人都可以请我吗?
https://codesandbox.io/s/strange-sanderson-wn3km?file=/demo.js
答案 0 :(得分:1)
根据错误,Material-UI Datagrid rows must have a column named id
。否则,它不会工作。您可以做的是像这样将所有 DT_RowId
键映射到 id
键,
const rowsBeforeMapping = [
{
DT_RowId: "1",
color: "red",
value: "#f00"
},
{
DT_RowId: "2",
color: "green",
value: "#0f0"
},
{
DT_RowId: "3",
color: "blue",
value: "#00f"
},
{
DT_RowId: "4",
color: "cyan",
value: "#0ff"
}
];
const rows = rowsBeforeMapping.map((row) => {
const { DT_RowId, ...rest } = row;
return { id: DT_RowId, ...rest };
});
答案 1 :(得分:1)
您可以使用 getRowId
属性返回您的唯一 ID DT_RowId
。(Material-ui DataGrid doc)
但它现在还有其他缺点。如果您想了解详情,请查看此issue #1119。 (在你的情况下,它不会影响,所以不用担心。)
我修改了您的代码并使其正常工作,例如:
import * as React from "react";
import { DataGrid } from "@material-ui/data-grid";
const columns = [
{ field: "DT_RowId", headerName: "DT_RowId(ID)", width: 150 },
{ field: "color", headerName: "Color", width: 100 },
{ field: "value", headerName: "Value", width: 130 }
];
const rows = [
{
DT_RowId: "1",
color: "red",
value: "#f00"
},
{
DT_RowId: "2",
color: "green",
value: "#0f0"
},
{
DT_RowId: "3",
color: "blue",
value: "#00f"
},
{
DT_RowId: "4",
color: "cyan",
value: "#0ff"
}
];
export default function DataTable() {
return (
<div style={{ height: 400, width: "100%" }}>
<DataGrid
getRowId={(r) => r.DT_RowId}
rows={rows}
columns={columns}
pageSize={5}
checkboxSelection
/>
</div>
);
}
希望能帮到你:)