首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React-table如何禁用客户端排序而只使用服务器端排序的数据

React-table如何禁用客户端排序而只使用服务器端排序的数据
EN

Stack Overflow用户
提问于 2020-11-02 15:54:04
回答 1查看 1.2K关注 0票数 1

我想使用服务器端排序的数据,并且想绕过react-table排序功能。我只想使用排序单击方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-04 19:08:33

要使用自定义可排序函数,可以使用两种不同的解决方案。

1/使用默认排序方法

您可以直接在ReactTable组件中使用defaultSortMethod属性,这里使用react-table库使用的默认方法,您可以用自己的方法替换它:

代码语言:javascript
复制
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的属性,您可以在其中调用自定义排序函数。

下面是一个按照长度进行自定义排序的示例:

代码语言:javascript
复制
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;
        }
      }
    ]
  }
]

这是the working example as a whole

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64641665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档