【问题标题】:React-table how to disable client-side sorting and use just server side Sorted DataReact-table 如何禁用客户端排序并仅使用服务器端排序数据
【发布时间】:2020-11-02 07:54:04
【问题描述】:

我想使用服务器端排序数据并想绕过反应表排序功能。我只想使用排序点击方法。

【问题讨论】:

    标签: react-table react-table-v6


    【解决方案1】:

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

    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;
            }
          }
        ]
      }
    ]
    

    这里是the working example as a whole

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 2017-12-28
      • 2017-03-21
      • 2010-09-24
      • 2012-02-20
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2020-04-28
      相关资源
      最近更新 更多