AntD的Table组件中的Sorter需要键盘可访问性,以便通过tab + enter来触发排序操作。我们可以使用onKeyDown
属性来检测按键事件,然后在按下Enter键时调用排序函数。
下面是一个示例代码:
import React from 'react';
import { Table } from 'antd';
class SortableTable extends React.Component {
handleKeyPress = (e, sorter) => {
if (e.key === 'Enter') {
sorter();
}
}
// 模拟数据
data = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
},
];
// 列配置
columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
sorter: (a, b) => a.name.localeCompare(b.name),
onHeaderCell: () => ({
onKeyDown: e => this.handleKeyPress(e, () => {
this.sorter.sort('name');
}),
}),
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
sorter: (a, b) => a.age - b.age,
onHeaderCell: () => ({
onKeyDown: e => this.handleKeyPress(e, () => {
this.sorter.sort('age');
}),
}),
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
sorter: (a, b) => a.address.localeCompare(b.address),
onHeaderCell: () => ({
onKeyDown: e => this.handleKeyPress(e, () => {
this.sorter.sort('address');
}),
}),
},
];
render