如何在MUI v6 DataGrid中仅显示默认列
解决MUI v6 DataGrid默认显示部分列、其余列可通过工具栏切换的问题
核心思路是不要过滤列数组,而是通过给列配置hide属性控制默认显示/隐藏,DataGrid的列选择器会自动识别所有列(无论是否隐藏),这样就能在GridToolbar里自由切换显示状态。
步骤1:定义完整列数组,设置默认隐藏属性
给需要默认隐藏的列添加hide: true,默认显示的列无需设置(或显式设为hide: false):
const columns = [ // 默认显示的列 { field: 'id', headerName: 'ID', width: 70 }, { field: 'name', headerName: '姓名', width: 130 }, { field: 'age', headerName: '年龄', width: 90 }, // 默认隐藏的列 { field: 'email', headerName: '邮箱', width: 200, hide: true }, { field: 'address', headerName: '地址', width: 250, hide: true }, { field: 'phone', headerName: '电话', width: 150, hide: true }, ];
步骤2:在DataGrid中使用完整列数组并启用工具栏
直接将完整列数组传给columns prop,同时配置GridToolbar组件:
import { DataGrid, GridToolbar } from '@mui/x-data-grid'; export default function CustomDataGrid() { // 替换为你的行数据 const rows = [ { id: 1, name: '张三', age: 25, email: 'zhangsan@example.com', address: '北京市朝阳区', phone: '13800138000' }, { id: 2, name: '李四', age: 30, email: 'lisi@example.com', address: '上海市浦东新区', phone: '13900139000' }, ]; return ( <div style={{ height: 400, width: '100%' }}> <DataGrid rows={rows} columns={columns} // 启用内置工具栏,包含列选择器 components={{ Toolbar: GridToolbar }} // 可选:持久化用户的列显示偏好(存在localStorage) onColumnVisibilityChange={(params) => { localStorage.setItem('dataGridColumnVisibility', JSON.stringify(params.columns)); }} // 可选:初始化时恢复用户之前的选择 initialState={{ columns: { visibilityModel: JSON.parse(localStorage.getItem('dataGridColumnVisibility')) || {}, }, }} /> </div> ); }
为什么之前的方法无效?
你之前通过useState过滤列数组,导致DataGrid仅接收到当前显示的列,列选择器自然只能识别这些列。而通过hide属性,DataGrid拿到的是完整列列表,列选择器会展示所有列,并根据hide状态标记勾选状态,用户可以自由切换显示/隐藏。
动态控制默认隐藏列(可选)
如果需要根据接口或其他逻辑动态设置默认显示的列,可以在列数组初始化时动态添加hide属性:
// 假设从接口获取默认显示的字段 const defaultVisibleFields = ['id', 'name', 'age']; const columns = [ { field: 'id', headerName: 'ID', width: 70 }, { field: 'name', headerName: '姓名', width: 130 }, { field: 'age', headerName: '年龄', width: 90 }, { field: 'email', headerName: '邮箱', width: 200 }, { field: 'address', headerName: '地址', width: 250 }, { field: 'phone', headerName: '电话', width: 150 }, ].map(col => ({ ...col, // 不在默认显示列表中的列设为隐藏 hide: !defaultVisibleFields.includes(col.field) }));
内容的提问来源于stack exchange,提问作者Pinak faldu
相关产品推荐
相关产品推荐

