You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React的MUI DataGrid中添加从0开始的序号ID列

解决MUI DataGrid将ID列改为从0开始的连续序号

要将ID列改为显示从0开始的连续序号,只需修改columns中ID列的valueGetter函数,利用DataGrid的API获取当前行在所有数据中的索引即可:

修改后的ID列配置

{
  field: "id",
  headerName: "ID",
  width: 70,
  valueGetter: (params) => params.api.getAllRows().indexOf(params.row),
}

完整修改后的组件代码

import React from "react";
import { DataGrid } from "@mui/x-data-grid";

const MainTable = ({ news }) => {
  const columns = [
    {
      field: "id",
      headerName: "ID",
      width: 70,
      valueGetter: (params) => params.api.getAllRows().indexOf(params.row),
    },
    { field: "title", headerName: "Title name", width: 200 },
    { field: "source", headerName: "Source", width: 130 },
    { field: "topic", headerName: "Topic", width: 80 },
    { field: "insight", headerName: "Insight", width: 130 },
    { field: "region", headerName: "Region", width: 200 },
    { field: "country", headerName: "Country", width: 200 },
    { field: "pestle", headerName: "Pestle", width: 130 },
    {
      field: "intensity",
      headerName: "Intensity",
      type: "number",
      width: 90,
    },
    {
      field: "relevance",
      headerName: "Relevance",
      type: "number",
      width: 90,
    },
    {
      field: "likelihood",
      headerName: "Likelihood",
      type: "number",
      width: 90,
    },
    {
      field: "end_year",
      headerName: "End Year",
      type: "number",
      width: 90,
    },
    {
      field: "start_year",
      headerName: "Start Year",
      type: "number",
      width: 90,
    },
    {
      field: "added",
      headerName: "Added",
      type: "date",
      width: 150,
    },
    {
      field: "published",
      headerName: "Published",
      type: "date",
      width: 150,
    },
    {
      field: "url",
      headerName: "URL",
      renderCell: (params) => {
        return <a href={`${params.row.url}`}>View</a>;
      },
      cellClassName: "text-gray-500 hover:underline",
      width: 130,
    },
  ];

  return (
    <div style={{ height: 650, width: "100%" }}>
      <DataGrid
        rows={news}
        columns={columns}
        pageSize={10}
        rowsPerPageOptions={[10]}
        getRowId={(row) => row._id}
      />
    </div>
  );
};

export default MainTable;

效果对比

  • 当前效果:
    当前效果截图

  • 预期效果:
    预期效果截图

原理说明

params.api.getAllRows()会返回DataGrid中的所有行数据数组,通过indexOf(params.row)获取当前行在数组中的索引,这个索引就是从0开始的连续序号,完全符合需求。

内容的提问来源于stack exchange,提问作者Nitin Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:00:58