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

5
首先,从服务器请求一些数据。然后我想添加一些数据。数据值中没有 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} />

但 index 是 NaN。当我添加新数据时,如何在表格中的每一行生成一个连续的序列号?

6个回答

3
我们可以使用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}/>

在上面的示例中,我假设code是一个唯一字段。如果很难有一个唯一的字段,您可以生成一个字段,其中包含code、type等组合。
在这种情况下,您的解决方案将类似于以下内容:
列字段:
   {
        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}/>

2

自从 MUI 发布了 6 版本,getRowIndex API 已被弃用。相反,您可以使用以下内容:

{
    field: "id",
    headerName: "number",
    filterable: false,
    renderCell: (index) =>
      index.api.getRowIndexRelativeToVisibleRows(index.row.code) + 1,
  }

getRowIndexRelativeToVisibleRows 获取相对于可滚动到的行的行索引。

参考: GridApi 接口


1

我认为之前的一些回答在API更改之前是有效的。

个人而言,我最近才开始使用MUI DataGrid组件。

我的解决方案与之前的答案非常相似。
getRowIndex6.0.2 中已不存在。
我找到的唯一API方法是 getRowIndexRelativeToVisibleRows,它似乎起到了作用(尽管“相对可见行”让我有点担心):

// ...

      {
        sortable: true,
        field: 'lineNo',
        headerName: '#',
        flex: 0,
        editable: false,
        renderCell: (params: GridRenderCellParams<DatasetEntryEntity>) =>
          params.api.getRowIndexRelativeToVisibleRows(params.row.id) + 1,
      },
// ...


0

我可以通过调用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等)。


0
最后一个答案给出了正确的结果,但有时会给出NaN,所以我正在使用这种类型。
renderCell: (params) => params.api.getAllRowIds().indexOf(params.id)+1

这个很好用,而且还告诉我是对还是错。

-2
你可以使用renderCell方法,其属性具有id键,该键对于每一行都是唯一的。它看起来会像这样。
renderCell: (params) => {
   return (<h1>
            {'serial Number:', params.id}
           </h1>);
        }

你也可以使用npm包nanoid为每一行生成一个唯一的ID。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接