在 Antd 表格中,可以通过设置 sorter
和 sortDirections
属性来实现排序,并通过设置 sorter
的 compare
属性自定义排序规则。
要忽略表格中的子元素,可以在 compare
方法中对子元素进行忽略。以下是一个示例代码:
import { Table } from 'antd';
import React from 'react';
const dataSource = [
{
key: '1',
name: 'John Brown',
age: 32,
children: [
{
key: '1-1',
name: 'John Brown Jr.',
age: 12,
},
{
key: '1-2',
name: 'John Brown Sr.',
age: 52,
},
],
},
// ...其他数据
];
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
sorter: (a, b) => {
// 忽略子元素的排序
return a.name.localeCompare(b.name, 'en', { ignorePunctuation: true });
},
sortDirections: ['ascend', 'descend'],
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
sorter: (a, b) => a.age - b.age,
sortDirections: ['ascend', 'descend'],
},
];
const DemoTable = () => {
return
;
};
export default DemoTable;
在上述代码中,我们通过在 sorter
方法中使用 localeCompare
方法对 name
字段进行排序,并设置 ignorePunctuation: true
来忽略子元素的影响。
对于 age
字段,我们直接使用数字的比较进行排序。
最后,将 dataSource
和 columns
传递给 Table
组件,即可实现忽略子元素的排序。