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

如何实现Material-UI DataGrid列标题自动换行?

Material-UI DataGrid 列标题自动换行实现方法

要实现类似Excel的列标题自动换行,你需要同时调整标题文本的换行属性和列标题容器的布局限制,以下是几种可行方案:

方案一:通过列定义的headerClassName单独设置

在列配置中给需要换行的标题添加自定义类,再通过CSS覆盖样式:

// 全局CSS或styled组件定义样式
.header-wrap {
  white-space: pre-wrap;
  word-wrap: break-word;
  line-height: 1.2;
  padding: 8px;
}

// 列配置示例
const columns = [
  {
    field: 'id',
    headerName: 'ID',
    width: 70
  },
  {
    field: 'longColumn',
    headerName: '这是一个需要自动换行的超长列标题',
    width: 200,
    headerClassName: 'header-wrap'
  }
];

// 使用DataGrid
<DataGrid rows={rows} columns={columns} />

方案二:全局覆盖所有列标题样式

如果需要所有列标题统一自动换行,可通过styled组件或sx属性完整覆盖样式:

import { DataGrid } from '@mui/x-data-grid';
import styled from '@emotion/styled';

const StyledDataGrid = styled(DataGrid)(({ theme }) => ({
  '& .MuiDataGrid-columnHeader': {
    height: 'auto', // 让表头高度自适应内容
    whiteSpace: 'normal' // 取消默认的不换行限制
  },
  '& .MuiDataGrid-columnHeaderTitle': {
    wordWrap: 'break-word',
    whiteSpace: 'pre-wrap',
    lineHeight: '1.3',
    padding: '10px 8px'
  }
}));

// 组件使用
<StyledDataGrid rows={rows} columns={columns} />

关键注意事项

  • 必须给列设置width或minWidth,否则列会自动拉伸至内容宽度,无法触发换行
  • 需同时修改容器(MuiDataGrid-columnHeader)和文本(MuiDataGrid-columnHeaderTitle)的样式,单独设置其中一个可能无效
  • 若不需要保留文本中的手动换行符,可将whiteSpace设为normal替代pre-wrap

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:40:03