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

如何基于角色权限等指定条件隐藏Material UI DataGrid的列?

问题根因

MUI DataGrid 的列配置项 hide 仅支持传入布尔值,你当前代码直接传入了hideColumn函数本身,组件不会自动执行该函数获取返回值,因此配置逻辑不生效。

解决方法

方案1:静态权限校验(页面加载后权限不会变更)

直接执行hideColumn函数,将返回的布尔值赋值给hide属性即可,修改后的代码如下:

const hideColumn = () => {
  const globalAdmin = auth.verifyRole(Roles.Admin);
  return !globalAdmin;
};

const columns = [
  { field: 'id', headerName: 'ID', width: 100 },
  { 
    field: 'name',
    headerName: 'Client code',
    flex: 1,
    hide: hideColumn(), // 执行函数拿到布尔返回值
    renderCell: (params) => {
      return params.getValue("name");
    },
  },
];

方案2:动态权限校验(页面运行中权限可能变更)

如果用户权限会在页面停留期间发生变化,需要将列配置做成响应式,配合useMemo监听权限变化自动更新列配置:

import { useMemo } from 'react';

// 组件内逻辑
const MyDataGrid = () => {
  // 权限校验结果
  const isGlobalAdmin = auth.verifyRole(Roles.Admin);
  
  const columns = useMemo(() => [
    { field: 'id', headerName: 'ID', width: 100 },
    { 
      field: 'name',
      headerName: 'Client code',
      flex: 1,
      hide: !isGlobalAdmin,
      renderCell: (params) => params.getValue("name"),
    },
  ], [isGlobalAdmin]); // 权限变化时重新生成列配置

  return <DataGrid columns={columns} {...其他组件参数} />
}

可选优化:直接过滤列

如果不希望列配置中存在无权限的列,也可以直接在生成列数组时过滤掉对应项:

const columns = [
  { field: 'id', headerName: 'ID', width: 100 },
  // 管理员才加入该列配置
  auth.verifyRole(Roles.Admin) && { 
    field: 'name',
    headerName: 'Client code',
    flex: 1,
    renderCell: (params) => params.getValue("name"),
  },
].filter(Boolean); // 过滤掉非管理员情况下的false项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:45:08