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

如何在MUI X Data Grid中实现含英文、日文及空值的自定义列排序

MUI X Data Grid 自定义排序实现

要实现你需要的排序规则,核心是给目标列配置sortComparator函数,覆盖默认排序逻辑。以下是具体实现步骤和完整代码:

1. 编写辅助判断函数

先实现一个判断字符串是否为英文的工具函数,同时处理空值/Null情况:

// 判断是否为英文内容(包含大小写字母,允许空值/Null)
const isEnglish = (value) => {
  if (value == null) return false;
  return /^[A-Za-z]+$/.test(value.trim());
};

2. 配置列的自定义排序函数

在需要自定义排序的列(比如firstName、lastName)中添加sortComparator属性,实现你的排序规则:

  • 升序:英文内容按A-Z排序,且优先排在非英文(日文)和空值之前;非英文和空值之间保持原有顺序或任意排列
  • 降序:英文内容按Z-A排序,且排在非英文(日文)和空值之后;非英文和空值之间保持原有顺序或任意排列

3. 完整修改后的代码

import * as React from "react";
import { DataGrid } from "@material-ui/data-grid";

const handleCellClick = (param, event) => {
  console.log(param);
  console.log(event);
  if (param.colIndex === 2) {
    event.stopPropagation();
  }
};

const handleRowClick = (param, event) => {
  console.log("Row:");
  console.log(param);
  console.log(event);
};

// 判断是否为英文内容
const isEnglish = (value) => {
  if (value == null) return false;
  return /^[A-Za-z]+$/.test(value.trim());
};

const columns = [
  {
    field: "id",
    headerName: "ID",
    width: 70
  },
  {
    field: "firstName",
    headerName: "First Name",
    width: 130,
    renderCell: (cellValues) => {
      return (
        <div
          style={{
            color: "blue",
            fontSize: 18,
            width: "100%",
            textAlign: "right"
          }}
        >
          {cellValues.value}
        </div>
      );
    },
    // 自定义排序函数
    sortComparator: (v1, v2, param) => {
      const isV1English = isEnglish(v1);
      const isV2English = isEnglish(v2);
      
      if (param.sortDirection === 'asc') {
        // 升序:英文在前,英文按A-Z排序
        if (isV1English && isV2English) {
          return v1.localeCompare(v2);
        }
        return isV1English ? -1 : isV2English ? 1 : 0;
      } else {
        // 降序:英文在后,英文按Z-A排序
        if (isV1English && isV2English) {
          return v2.localeCompare(v1);
        }
        return isV1English ? 1 : isV2English ? -1 : 0;
      }
    }
  },
  { 
    field: "lastName", 
    headerName: "Last Name", 
    width: 130,
    // 同样添加自定义排序函数
    sortComparator: (v1, v2, param) => {
      const isV1English = isEnglish(v1);
      const isV2English = isEnglish(v2);
      
      if (param.sortDirection === 'asc') {
        if (isV1English && isV2English) {
          return v1.localeCompare(v2);
        }
        return isV1English ? -1 : isV2English ? 1 : 0;
      } else {
        if (isV1English && isV2English) {
          return v2.localeCompare(v1);
        }
        return isV1English ? 1 : isV2English ? -1 : 0;
      }
    }
  },
  {
    field: "age",
    headerName: "Age",
    type: "number",
    minWidth: 90,
    flex: 1
  },
  {
    field: "fullName",
    headerName: "Full name",
    description: "This column has a value getter and is not sortable.",
    sortable: false,
    minWidth: 160,
    flex: 2,
    valueGetter: (params) => {
      return `${params.getValue(params.id, "firstName") || ""} ${
        params.getValue(params.id, "lastName") || ""
      }`;
    }
  }
];

const rows = [
  { id: 1, lastName: "Snow", firstName: "Jon", age: 35 },
  { id: 2, lastName: "Lannister", firstName: "Amy", age: 42 },
  { id: 3, lastName: "IGOTAREALL", firstName: "Jaime", age: 45 },
  { id: 4, lastName: "Stark", firstName: "Arya", age: 16 },
  { id: 5, lastName: "Targaryen", firstName: "Daenerys", age: 12 },
  { id: 6, lastName: "Melisandre", firstName: "Jane", age: 15 },
  { id: 7, lastName: "榎原", firstName: "しよう", age: 44 },
  { id: 8, lastName: "田中", firstName: "田畑", age: 36 },
  { id: 9, lastName: "瀬奈", firstName: "健治", age: 65 },
  // 添加空值测试行
  { id: 10, lastName: null, firstName: "", age: 28 }
];

export default function DataGridDemo() {
  return (
    <div style={{ height: 500, width: "100%" }}>
      <DataGrid
        rowHeight={50}
        className={"hello"}
        rows={rows}
        columns={columns}
        pageSize={10}
        checkboxSelection
        onCellClick={handleCellClick}
        onRowClick={handleRowClick}
      />
    </div>
  );
}

关键说明

  • sortComparator函数接收三个参数:当前单元格值v1、对比单元格值v2、包含排序方向的参数对象param
  • 利用localeCompare实现英文的自然排序,如需区分大小写可添加参数{ sensitivity: 'case' }
  • 非英文和空值的排序通过返回0保持原有顺序,你也可以根据需求调整这部分逻辑(比如按日文假名排序)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:30:57