我想使用服务器端排序的数据,并且想绕过react-table排序功能。我只想使用排序单击方法。
发布于 2021-01-04 19:08:33
要使用自定义可排序函数,可以使用两种不同的解决方案。
1/使用默认排序方法
您可以直接在ReactTable组件中使用defaultSortMethod属性,这里使用react-table库使用的默认方法,您可以用自己的方法替换它:
defaultSortMethod: (a, b, desc) => {
// force null and undefined to the bottom
a = a === null || a === undefined ? '' : a
b = b === null || b === undefined ? '' : b
// force any string values to lowercase
a = typeof a === 'string' ? a.toLowerCase() : a
b = typeof b === 'string' ? b.toLowerCase() : b
// Return either 1 or -1 to indicate a sort priority
if (a > b) {
return 1
}
if (a < b) {
return -1
}
// returning 0, undefined or any falsey value will use subsequent sorts or
// the index as a tiebreaker
return 0
},2/指定特定列的排序方式
您可以在列中添加名为sortMethod的属性,您可以在其中调用自定义排序函数。
下面是一个按照长度进行自定义排序的示例:
columns={[
{
Header: "Name",
columns: [
{
Header: "First Name (Sorted by Length, A-Z)",
accessor: "firstName",
sortMethod: (a, b) => {
if (a.length === b.length) {
return a > b ? 1 : -1;
}
return a.length > b.length ? 1 : -1;
}
},
{
Header: "Last Name (Sorted in reverse, A-Z)",
id: "lastName",
accessor: d => d.lastName,
sortMethod: (a, b) => {
if (a === b) {
return 0;
}
const aReverse = a.split("").reverse().join("");
const bReverse = b.split("").reverse().join("");
return aReverse > bReverse ? 1 : -1;
}
}
]
}
]https://stackoverflow.com/questions/64641665
复制相似问题