我正在创建一个 DataGrid,我想在其中显示
ready_by
和 name
的值,您可以在这张图片中看到:
代码中我是这样配置的:(重点看最后两条)
const columns = [
{
field: 'id',
headerName: "ID",
minWidth: 50,
type:"number",
align:'left',
hide:'true'
},
{
field: 'customer',
headerName: 'Customer',
valueGetter: ({ value }) => value.email,
width: 250,
},
{
field: 'paid',
headerName: 'Customer has paid?',
width: 250,
},
{
field: 'total',
headerName: 'Cost',
width: 150,
},
{
field: 'details',
headerName: 'Ready By',
type: 'datetime',
valueGetter: ({ value }) => value.ready_by && new Date(value.ready_by),
width: 250,
},
{
field: 'details',
headerName: 'Name',
valueGetter: ({ value }) => value[0].name,
width: 250,
},
];
问题是,当我渲染页面时,只显示其中一个,这是因为我重复了
field
值。所以我想请教一下你如何解决这个问题:
是的,这是正确的。 “字段”是列标识符,必须是唯一的。
这是我的解决方案:
假设:这里
data
表示您要提供给 rows
MUI 组件的 <DataGrid/>
属性的数组。
const columns = React.useMemo(
() => [
..., // all the other elements
// No changes needed here since this is the first occurrence of 'details'
{
field: 'details',
headerName: 'Ready By',
type: 'datetime',
valueGetter: ({ value }) => value.ready_by && new Date(value.ready_by),
width: 250,
},
// Here we're basically searching for the item of interest since we do get `id` as a param arg.
{
field: 'details2',
headerName: 'Name',
valueGetter: ({ id }) => {
const item = data.find(item => item.id === id);
return item.name;
},
width: 250,
},
],
[data]
)
params
中的 ValueGetter
对象包含一个 row
属性,该属性包含映射行的整个模型。因此,您只需在 field
中分配一个唯一的 ID(不必与对象上的属性匹配),然后从 params.row
获取值。例如
...
// Leave this one the same
{
field: 'details',
headerName: 'Ready By',
type: 'datetime',
valueGetter: ({ value }) => value.ready_by && new Date(value.ready_by),
width: 250,
},
// Set a unique field and get the relevant data using the row property
{
field: 'name',
headerName: 'Name',
valueGetter: (params) => params.row.details[0].name,
width: 250,
},
...
这比在整个数据列表上使用
find()
更有效,因为我们已经知道该行的具体模型。
ValueGetter
的参数类型为GridValueGetterParams
。关于此类型的文档不多,但根据来源,它扩展了GridCellParams
,其中包含一些关于row
的信息。