javascript - 如何为 MUI DataGrid 中的每一行添加一个序列号?

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

https://stackoverflow.com/questions/71822341/

相关文章:

node.js - 在 Github 操作中获取错误 : connect ECONNREFUSED

c# - 触发 SelectedIndexChanged 后列表框在视觉上卡住

python - 以两种方式遍历列表但无法理解行为

javascript - 在 Promise.all 中 react setState

java - 使用 'fib(N) = [Phi^N – phi^N]/Sqrt[5]' 公式计算

javascript - OpenSea 错误 - 请使用 providerUtils.standa

xamarin - MAUI Shell 从侧面移除 OverScroll

html - 如何用 CSS 连接大写单词?

python - 使用 Pandas Align 时,时间序列数据帧返回错误 - valueErro

reactjs - 组件 Prop 中不兼容的函数参数