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

MUI X V4 Data Grid:如何按Age字段实现行的条件字体着色

解决MUI X V4 Data Grid中指定行字体变灰的问题

方法一:使用getRowStyle直接设置内联样式

在DataGrid组件中添加getRowStyle属性,通过回调函数动态判断行数据并返回样式:

import * as React from "react";
import { DataGrid } from "@material-ui/data-grid";

// 原columns和rows定义不变

export default function App() {
  const [selectionModel, setSelectionModel] = React.useState([]);
  return (
    <div style={{ height: 400, width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={25}
        checkboxSelection
        hideFooterPagination
        onSelectionModelChange={(newSelection) => {
          setSelectionModel(newSelection.selectionModel);
        }}
        selectionModel={selectionModel}
        // 新增行样式判断逻辑
        getRowStyle={(params) => {
          return params.row.age === 16 ? { color: 'grey' } : {};
        }}
      />
      {selectionModel.map(val => <h1>{val}</h1>)}
    </div>
  );
}

getRowStyle是MUI X V4 DataGrid内置的回调属性,每行渲染时都会触发,参数params包含当前行的完整数据,通过判断row.age的值即可返回对应的样式对象。

方法二:使用rowClassName结合CSS类(适合复杂样式)

如果需要添加更多样式属性,推荐用CSS类的方式:

import * as React from "react";
import { DataGrid } from "@material-ui/data-grid";
import { makeStyles } from "@material-ui/core/styles";

// 定义CSS类
const useStyles = makeStyles({
  greyRow: {
    color: 'grey',
    // 可扩展其他样式,比如背景色
    // backgroundColor: '#f5f5f5'
  }
});

// 原columns和rows定义不变

export default function App() {
  const classes = useStyles();
  const [selectionModel, setSelectionModel] = React.useState([]);
  return (
    <div style={{ height: 400, width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={25}
        checkboxSelection
        hideFooterPagination
        onSelectionModelChange={(newSelection) => {
          setSelectionModel(newSelection.selectionModel);
        }}
        selectionModel={selectionModel}
        // 动态绑定类名
        rowClassName={(params) => params.row.age === 16 ? classes.greyRow : ''}
      />
      {selectionModel.map(val => <h1>{val}</h1>)}
    </div>
  );
}

原有方法无效的原因

你尝试直接返回<TableRow>的方式不生效,是因为MUI X DataGrid内部已经封装了行的渲染逻辑,不允许外部直接替换行元素。必须通过组件提供的getRowStyle、rowClassName这类官方API来实现行样式的自定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:33:22