首先向服务器请求一些数据。然后我想添加一些数据。数据值中没有ID,但是表单需要显示序列号。
const columns: GridColDef[] = [
{
field: 'id' ,
headerName: 'number',
filterable: false,
renderCell:(index:any) => `${index + 1}`
},
{ field: 'code' , headerName: ' code' },
{ field: 'type' , headerName: ' type' },
]
<DataGrid rows={row} columns={columns} />
但是索引是Nan。如何在添加新数据时在表中的每一行生成一个序列号?
我们可以使用
getRowIndex
方法来实现。
getRowIndex
方法将文件名作为参数,并返回该文件所属行的索引。所以诀窍是将一个独特的领域传递给这个方法。
你的问题的解决方案看起来像这样:
列字段:
{
field: 'id' ,
headerName: 'number',
filterable: false,
renderCell:(index) => index.api.getRowIndex(index.row.code)
}
数据网格:
<DataGrid rows={row} columns={columns} getRowId= {(row) => row.code}/>
在上面的示例中,我假设代码是一个唯一字段。如果很难有一个唯一的字段,你可以用代码、类型等的组合生成一个字段。
在这种情况下,您的解决方案将如下所示:
列字段:
{
field: 'id' ,
headerName: 'number',
filterable: false,
renderCell:(index) => index.api.getRowIndex(index.row.code + '_' + index.row.type)
}
数据网格:
<DataGrid rows={row} columns={columns} getRowId= {(row) => row.code + '_' + row.type}/>
我能够通过从 api 调用
getRowIndex
来获取行索引:
renderCell: (index) => index.api.getRowIndex(index.row.id) + 1,
所以用你的例子:
const columns: GridColDef[] = [
{
field: 'id' ,
headerName: 'number',
filterable: false,
renderCell: (index) => index.api.getRowIndex(index.row.id) + 1,
},
{ field: 'code' , headerName: ' code' },
{ field: 'type' , headerName: ' type' },
]
如果列有
sortable: true
,则无论列如何排序,此索引号都不会改变 - 第一行项始终为 1,第二行项始终为 2,以此类推。
同样,对于启用分页的网格,索引将根据页面进行匹配(即:如果每页有 5 个行项目,无论排序如何,第 1 页的第一个行项目始终为 1,第 2 页的 6,等)。
我假设之前的一些答案在他们更改 API 之前是有效的。
就个人而言,我最近才开始使用 MUI DataGrid 组件。
我的解决方案与之前的答案非常相似。
getRowIndex
不存在于6.0.2
.getRowIndexRelativeToVisibleRows
,它似乎可以解决问题(尽管“相对于可见行”确实让我有点担心):
// ...
{
sortable: true,
field: 'lineNo',
headerName: '#',
flex: 0,
editable: false,
renderCell: (params: GridRenderCellParams<DatasetEntryEntity>) =>
params.api.getRowIndexRelativeToVisibleRows(params.row.id) + 1,
},
// ...
你可以使用 renderCell 方法,它的 prop 有一个 id 键,它对每一行都是唯一的。它看起来像这样。
renderCell: (params) => {
return (<h1>
{'serial Number:', params.id}
</h1>);
}
您还可以使用 npm 包 nanoid 为每一行生成一个唯一的 id。