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

Material UI DataGrid v5 React行交替着色实现失败求助

解决Material UI v5 DataGrid行交替着色无效的问题

你的代码里getRowClassName的逻辑是对的,但没生效大概率是自定义样式优先级不够,被DataGrid默认行样式覆盖了,下面给你两种可行的解决方法:

方法一:提升自定义类样式优先级

修改你的style.css,用更精准的选择器来覆盖默认样式:

/* 结合DataGrid的行类名,提升样式优先级 */
.MuiDataGrid-row.blue {
  background-color: #e3f2fd; /* 替换成你想要的蓝色 */
}

.MuiDataGrid-row.black {
  background-color: #ffffff; /* 白色行 */
}

同时修正Table.js里重复的style属性(不影响功能但更规范):

import * as React from "react";
import { DataGrid } from "@mui/x-data-grid";
import "./style.css";

export default function DataTable(props) {
  return (
    <div style={{ height: 585, width: "100%" }}>
      <DataGrid
        style={{ letterSpacing: "1px" }}
        rows={props.rows}
        columns={props.columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
        getRowClassName={(params) =>
          params.indexRelativeToCurrentPage % 2 === 0 ? 'blue' : 'black'
        }
        sx={{
          fontFamily: 'Montserrat',
          fontSize: '14px',     
          fontWeight: 550,
          color: "black",
          backgroundColor: "#FAF9F6",
        }}
      />
    </div>
  );
}

方法二:直接用sx嵌套选择器(更简洁)

不需要自定义类,直接在DataGrid的sx属性里设置奇偶行样式,利用gridClasses.row定位行元素:

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

export default function DataTable(props) {
  return (
    <div style={{ height: 585, width: "100%" }}>
      <DataGrid
        style={{ letterSpacing: "1px" }}
        rows={props.rows}
        columns={props.columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
        sx={{
          fontFamily: 'Montserrat',
          fontSize: '14px',     
          fontWeight: 550,
          color: "black",
          backgroundColor: "#FAF9F6",
          // 设置偶数行背景色
          [`& .${gridClasses.row}:nth-of-type(even)`]: {
            backgroundColor: '#e3f2fd',
          },
          // 设置奇数行背景色
          [`& .${gridClasses.row}:nth-of-type(odd)`]: {
            backgroundColor: '#ffffff',
          },
        }}
      />
    </div>
  );
}

这种方式不用额外写CSS文件,直接通过Material UI的sx语法实现,优先级也足够覆盖默认样式。

内容的提问来源于stack exchange,提问作者Jigyasa Nagpal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:20:43