如何解决如何为React Table 7提供自定义排序功能?
useSortBy sortType属性的documention说:
sortType: String | Function(rowA: <Row>,rowB: <Row>,columnId: String,desc: Bool)
Used to compare 2 rows of data and order them correctly.
If a function is passed,it must be memoized. The sortType function should return -1 if rowA is larger,and 1 if rowB is larger. react-table will take care of the rest.
String options: basic,datetime,alphanumeric. Defaults to alphanumeric.
The resolved function from the this string/function will be used to sort the this column's data.
If a string is passed,the function with that name located on either the custom sortTypes option or the built-in sorting types object will be used.
If a function is passed,it will be used.
For more information on sort types,see Sorting
那么如何提供sortType函数呢?
解决方法
sortType函数的参数为: (rowA,rowB,columnId,desc)
columnId
标识该行被排序的列,因此可以获取单元格值。
desc
标识排序的方向。即使提供了desc
,排序函数也应该不反转返回值。 react表会自动执行此操作。
例如:
sortType: React.useMemo((rowA,rowB,id,desc) => {
if (rowA.original[id] > rowB.original[id]) return -1;
if (rowB.original[id] > rowA.original[id]) return 1;
return 0;
})
,
我也很难弄清楚这个问题。这是我如何做到的。它在打字稿中,但如果您需要在纯 js 中使用它,只需删除所有类型即可。第一,这里是自定义排序。它将对字符串进行排序,并始终将空值/空白/未定义放在末尾。
const customStringSort: any = (rowA: Row,rowB: Row,columnId: string,desc: boolean) => {
const defaultVal = desc ? 'AAAAAAAAAAAA' : 'ZZZZZZZZ';
return (rowA.values[columnId] ?? defaultVal)
.localeCompare(rowB.values[columnId] ?? defaultVal);
};
有两件事需要注意。
- 当返回值定义为数字时,我不明白为什么 typescript 不喜欢它。我讨厌使用任何一个,但这是有效的。
- react table 文档表明必须记住这一点。这不是,但它仍然有效。
接下来,您必须将此函数添加到 sortTypes。
const sortTypes: Record<string,SortByFn<SomeObject>> = {
customStringSort: customStringSort,};
接下来,将 sortTypes 添加到 useTable 实例中。
const {
getTableProps,getTableBodyProps
headerGroups,rows,prepareRow,} = useTable(
{
columns,data,sortTypes
},useSortBy
);
现在您可以将自定义函数添加到列定义中。
const columns: Column<SomeObject>[] = React.useMemo(() =>
[
{ accessor: 'someColumnID',Header: 'Some Column',sortType:'customStringSort' },],[],);
希望这会有所帮助!
--编辑:如果你想记住这个函数,这很有效。只需在适当的地方用 customStringSortMemo 替换 customStringSort。
const customStringSort: any = React.useCallback((rowA: Row,desc: boolean) =>
{
const defaultVal = desc ? 'AAAAAAAAAAAA' : 'ZZZZZZZZ';
return (rowA.values[columnId] ?? defaultVal).localeCompare(rowB.values[columnId] ?? defaultVal);
},[]);
const customStringSortMemo = React.useMemo(() => customStringSort[customStringSort]);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。