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

MUI Datagrid自定义排序图标问题:区分未排序与已排序列图标

MUI DataGrid 自定义排序图标问题解决方法

核心问题是全局Slots无法获取单列的排序状态,因此要放弃全局配置,改用列级别自定义排序图标,让每个列的图标能判断自身是否为当前排序列。

步骤1:定义自定义排序图标组件

这个组件接收当前列的排序方向、字段名,以及全局的排序模型,根据对比结果返回对应图标:

import UnsortIcon from '@mui/icons-material/UnfoldMore';
import AscIcon from '@mui/icons-material/ArrowUpward';
import DescIcon from '@mui/icons-material/ArrowDownward';

const CustomSortIcon = ({ sortDirection, field, sortModel }) => {
  const isActiveSort = sortModel[0]?.field === field;
  if (!isActiveSort) {
    // 未排序时显示自定义未排序图标
    return <UnsortIcon />;
  }
  // 已排序时根据方向显示对应图标
  return sortDirection === 'asc' ? <AscIcon /> : <DescIcon />;
};

步骤2:在列定义中配置自定义图标

给所有6列(包括2个自定义排序列)配置sortIcon属性,传入当前列的信息和全局排序模型:

// 假设你的自定义排序函数已经定义好
const customSortFunc1 = (a, b) => {
  // 自定义排序逻辑
};
const customSortFunc2 = (a, b) => {
  // 自定义排序逻辑
};

const columns = [
  {
    field: 'customCol1',
    headerName: '自定义列1',
    sortComparator: customSortFunc1,
    sortIcon: (props) => <CustomSortIcon {...props} sortModel={sortModel} />
  },
  {
    field: 'customCol2',
    headerName: '自定义列2',
    sortComparator: customSortFunc2,
    sortIcon: (props) => <CustomSortIcon {...props} sortModel={sortModel} />
  },
  // 其他4个普通列同样配置
  {
    field: 'normalCol1',
    headerName: '普通列1',
    sortIcon: (props) => <CustomSortIcon {...props} sortModel={sortModel} />
  },
  {
    field: 'normalCol2',
    headerName: '普通列2',
    sortIcon: (props) => <CustomSortIcon {...props} sortModel={sortModel} />
  },
  // 剩下两列同理
];

步骤3:在DataGrid中维护/获取排序模型

通过useState维护排序模型,或者用apiRef直接获取:

import { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';

const MyDataGrid = () => {
  const [sortModel, setSortModel] = useState([]);
  const rows = [/* 你的数据 */];

  return (
    <DataGrid
      rows={rows}
      columns={columns}
      sortModel={sortModel}
      onSortModelChange={setSortModel}
      autoHeight
    />
  );
};

原理说明

  • 全局Slots的SortIcon无法获取单个列的field信息,所以无法区分当前列是否为排序列,导致所有列图标统一。
  • 列级别配置sortIcon时,组件能拿到当前列的field和sortDirection,再结合全局sortModel,就能精准判断该列是否处于排序状态,从而显示对应图标。

内容的提问来源于stack exchange,提问作者Pramod Kumar Koppu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:15:19