如何向 MUI DataGrid 中的每一行添加序列号?

Ath*_*run 5 javascript datagrid typescript reactjs material-ui

首先,向服务器请求一些数据。然后我想添加一些数据。数据值中没有ID,但表单需要显示序列号。

 const columns: GridColDef[] = [
        { 
            field: 'id' , 
            headerName: 'number', 
            filterable: false,
            renderCell:(index:any) => `${index + 1}`
        },
        { field: 'code' , headerName: ' code' },
        { field: 'type' , headerName: ' type' },
  ]
Run Code Online (Sandbox Code Playgroud)
<DataGrid rows={row} columns={columns} />
Run Code Online (Sandbox Code Playgroud)

但索引是Nan。当我添加新数据时,如何在表中的每一行生成序号?

Jus*_*rks 0

getRowIndex我能够通过从 api调用来获取行索引:

renderCell: (index) => index.api.getRowIndex(index.row.id) + 1,
Run Code Online (Sandbox Code Playgroud)

所以用你的例子:

 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' },
  ]
Run Code Online (Sandbox Code Playgroud)

如果某列具有sortable: true,则无论该列如何排序,此索引号都不会更改 - 第一个行项目始终为 1,第二个行项目为 2,依此类推。

同样,对于启用分页的网格,索引将根据页面进行匹配(即:如果每页有 5 个行项目,无论排序如何,第一个行项目将始终为第 1 页上的 1、第 2 页上的 6 个等)。