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

MUI X Data Grid快速水平滚动时表头背景色错位问题求助

MUI X Data Grid 表头滚动颜色错位问题解决

问题场景

在React(NextJS)项目中使用MUI X Data Grid实现表格,给表头列设置不同背景色后,快速水平滚动时表头颜色会整体偏移一列,比如原本黄色的“rank”列会变成红色:

正常效果:
表头正常效果

滚动错位效果:
表头颜色错位效果

问题原因

你当前通过:nth-child()选择器基于DOM节点的位置来设置表头样式,但MUI X Data Grid在水平滚动时,会对表头列的DOM元素进行动态复用或重排,导致DOM节点的顺序和视觉上的列顺序暂时不一致,从而出现颜色错位。这种依赖DOM结构固定顺序的样式写法,不适合Data Grid这类动态列容器。

解决方法

改用列配置绑定样式的方式,给每个列对象添加专属的headerClassName,再通过类名设置样式,让样式和列本身绑定,不受DOM结构变化影响。

步骤1:修改列生成逻辑,添加headerClassName

在getColumns函数中,给每个列绑定对应的样式类名:

const getColumns = () => {
  // 按原顺序定义列对应的颜色类名
  const columnColorClasses = [
    'header-black', 'header-black',
    'header-gray', 'header-gray', 'header-gray', 'header-gray',
    'header-dark-red', 'header-blue', 'header-red',
    'header-yellow', 'header-yellow', 'header-yellow',
    'header-light-blue', 'header-light-blue',
    'header-teal',
    'header-green', 'header-green', 'header-green'
  ];
  let columns = [];
  let classIndex = 0;
  for(let i = 0; i < dataSubdirecciones.length; i++){
      for(let j = 0; j < dataSubdirecciones[i].datosAgrupadorList.length; j++){
        columns.push({
          field: dataSubdirecciones[i].datosAgrupadorList[j].nombreDato,
          headerName: dataSubdirecciones[i].datosAgrupadorList[j].nombreDato,
          width: 130,
          headerClassName: columnColorClasses[classIndex], // 绑定专属类名
          renderHeader: (params) => (
            <div>
              {
                splitString(dataSubdirecciones[i].datosAgrupadorList[j].nombreDato).map((word) => (
                  <React.Fragment key={word}>
                    {word}
                    <br />
                  </React.Fragment>
                ))
              }
            </div>
          ),
        });
        classIndex++;
      }
  }
  return columns;
}

步骤2:重构样式对象,用类名替代:nth-child()

修改MAIN_TABLES_HEADER_STYLES,通过类名设置对应样式:

const MAIN_TABLES_HEADER_STYLES = {
  '& .MuiDataGrid-columnHeaderTitleContainer': {
    lineHeight: 1.5,
  },
  '.MuiDataGrid-columnSeparator': { display: 'none' },
  '&.MuiDataGrid-root': { border: 'none' },
  // 按类名设置样式
  '& .header-black': {
    backgroundColor: '#000000',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .header-gray': {
    backgroundColor: '#9e9e9e',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .header-dark-red': {
    backgroundColor: '#6f0000',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .header-blue': {
    backgroundColor: '#0075ad',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .header-red': {
    backgroundColor: '#d20000',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .header-yellow': {
    backgroundColor: '#ffd600',
    color: '#000000',
    fontWeight: 'bold',
  },
  '& .header-light-blue': {
    backgroundColor: '#70b7bc',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .header-teal': {
    backgroundColor: '#009f94',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .header-green': {
    backgroundColor: '#1e9a00',
    color: '#ffffff',
    fontWeight: 'bold',
  },
}

优化点:避免不必要的重渲染

你的组件中DataGrid直接调用getRows()和getColumns(),每次渲染都会重新生成列和行数据,建议改用useEffect缓存的columnsName和rows:

<DataGrid 
  sx={headerStyles}
  rows={rows}
  columns={columnsName}
  hideFooterPagination={true}
  hideFooter={true}
  headerHeight={50}
  pageSize={10}
/>

效果说明

这种方式将样式与列的配置绑定,不管DOM结构如何动态调整,每个列的表头都会应用对应的样式,彻底解决滚动时的颜色错位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:04:59