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

如何修改DataGrid组件中列面板的max-height属性

修改@material-ui/data-grid v4列面板的max-height

针对你使用的@material-ui/data-grid ^4.0.0-alpha.8版本,直接给GridColumnsPanel添加className设置max-height不生效的原因是:列面板的滚动区域样式定义在其内部的子容器上,而非根组件本身。你需要通过深度CSS选择器定位到内部的滚动容器来修改样式。

解决方案1:使用makeStyles深度选择器

修改你的样式定义,通过外层类名嵌套定位到内部的滚动容器:

import {
  DataGrid,
  GridToolbarContainer,
  GridToolbarColumnsButton,
  GridColumnsPanel,
} from '@material-ui/data-grid';
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
  columnsPanel: {
    // 定位到列面板内部的滚动列表容器
    '& .MuiGridColumnsPanel-list': {
      maxHeight: '282px',
      overflowY: 'auto', // 确保内容超出时显示滚动条
    },
  },
}));

const CustomColumnsPanel = ({ children }) => {
  const classes = useStyles();
  return <GridColumnsPanel className={classes.columnsPanel}>{children}</GridColumnsPanel>;
};

const TableList = ({ ...props }) => {
  // ... 其他代码 ...

  return (
    <Box>
      <DataGrid
        rows={rows}
        columns={columns}
        components={{
          Toolbar: CustomToolbar,
          ColumnsPanel: CustomColumnsPanel
        }}
      />
    </Box>
  );
};

解决方案2:使用styled组件

如果makeStyles的深度选择器不生效,可以尝试用styled组件直接封装GridColumnsPanel:

import {
  DataGrid,
  GridToolbarContainer,
  GridToolbarColumnsButton,
  GridColumnsPanel,
} from '@material-ui/data-grid';
import styled from '@material-ui/core/styles/styled';

const CustomColumnsPanel = styled(GridColumnsPanel)`
  .MuiGridColumnsPanel-list {
    max-height: 282px;
    overflow-y: auto;
  }
`;

const TableList = ({ ...props }) => {
  // ... 其他代码 ...

  return (
    <Box>
      <DataGrid
        rows={rows}
        columns={columns}
        components={{
          Toolbar: CustomToolbar,
          ColumnsPanel: CustomColumnsPanel
        }}
      />
    </Box>
  );
};

验证类名准确性

如果上述代码仍不生效,你可以通过浏览器开发者工具查看列面板的DOM结构,确认内部滚动容器的类名(通常是类似MuiGridColumnsPanel-list的格式),替换代码中的类名即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:33:38