我的用例略有不同,我希望在初始加载时以默认的多重排序方式进行排序,但是在未来的任何排序操作之后也保持该排序顺序。
这里有一个沙盒示例:
https://codesandbox.io/s/goofy-shadow-9tskr?file=/src/App.js
诀窍在于不使用内置的getSortByToggleProps()函数,而是添加自己的onClick事件,使用setSortBy()函数。
以下代码来源于@khai nguyen的答案
import React from 'react'
import { useTable, useSortBy } from 'react-table';
function Table({ columns, data, sortBy ...rest }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
setSortBy,
} = useTable({
columns,
data,
initialState: {sortBy}
})
}, useSortBy);
接下来,在您的列标题元素中:
...PREV_TABLE_CODE
{headerGroup.headers.map(column => (
<th
{...column.getHeaderProps()}
onClick={() => handleMultiSortBy(column, setSortBy, sortBy)}
>
{column.render(
REST_TABLE_CODE....
还有 handleMultiSortByCode
(我的自定义函数,不是来自 react-table 库):
isSortedDesc
可以是 true、false 或 undefined。
export const handleMultiSortBy = (column, setSortBy, meinSortBy) => {
const desc =
column.isSortedDesc === true
? undefined
: column.isSortedDesc === false
? true
: false;
setSortBy([{ id: column.id, desc }, ...meinSortBy]);
};
注意:默认的toggleSortBy()函数中有一个e.persist()。我不确定它起到了什么作用,但不使用它似乎没有任何不良影响 - 原生的多重排序(按住shift)不起作用,但添加回去也无法修复。猜测您可能需要原生的toggleSort来解决这个问题。