如何为 React table 7 提供自定义排序功能?

How does one supply a custom sort function for 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,排序函数也应该 NOT 反转 return 值。 react table 自动执行此操作。

例如:

sortType: React.useMemo((rowA, rowB, id, desc) => {
       if (rowA.values[id] > rowB.values[id]) return 1; 
       if (rowB.values[id] > rowA.values[id]) return -1;
        return 0;
})

使用 sortType 的示例:

const columns = [{       
        Header: ...
        accessor: ...
        sortType: /*sortType func goes here... */        
}, ...]

function MyTable(columns, data)
{
 const { /*...*/ } = useTable({columns,data})
}

我也很难弄清楚这个问题。我是这样做的。它是打字稿,但如果你需要它在纯 js 中,只需删除所有打字。第一,这里是自定义排序。它会对字符串进行排序,并始终将 nulls/blanks/undefined 放在末尾。

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

对此有两点需要注意。

  1. 当 return 被定义为数字时,我不明白为什么打字稿不喜欢它。我讨厌使用任何一个,但这有效。
  2. 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, rowB: Row, columnId: string, desc: boolean) => 
  {
  const defaultVal = desc ? 'AAAAAAAAAAAA' : 'ZZZZZZZZ';
  return (rowA.values[columnId] ?? defaultVal).localeCompare(rowB.values[columnId] ?? defaultVal);
  },
[]);
    
const customStringSortMemo = React.useMemo(() => customStringSort[customStringSort]);

根据您的文档引用,sortType 是 Column option

The following options are supported on any Column object passed to the columns options in useTable()

例如,修改快速入门的Define Columns,像这样:

const columns = React.useMemo(
  () => [
    {
      Header: 'Column 1',
      accessor: 'col1', // accessor is the "key" in the data
    },
    {
      Header: 'Column 2',
      accessor: 'col2',
      sortType: compareNumericString // custom function
    },
  ],
  []
)

function compareNumericString(rowA, rowB, id, desc) {
    let a = Number.parseFloat(rowA.values[id]);
    let b = Number.parseFloat(rowB.values[id]);
    if (Number.isNaN(a)) {  // Blanks and non-numeric strings to bottom
        a = desc ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
    }
    if (Number.isNaN(b)) {
        b = desc ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
    }
    if (a > b) return 1; 
    if (a < b) return -1;
    return 0;
}

自定义排序 ini 最后 Header 在常量列中

const columns = React.useMemo(
            () => [
              {
                Header: 'ID',
                accessor: 'IDXX_GRPX'
              },
              {
                Header: 'Nama Group',
                accessor: 'NAMA_GRPX'
              },
              {
                Header: 'Kecamatan',
                accessor: 'KECX_DESC'
              },
              {
                Header: 'Kelurahan',
                accessor: 'AREA_DESC'
              },
              {
                Header: 'Unit',
                accessor: 'BUSS_CODE'
              },
              {
                Header: 'Kode Urut',
                accessor: 'KODE_URUT',
                sortType: (a, b) => {
                      if (a.values['KODE_URUT'] < b.values['KODE_URUT']) {
                          return -1;
                      } else if (a.values['KODE_URUT'] > b.values['KODE_URUT']) {
                          return 1;
                      };
    
                      return 0;
                  }
              }
            ],
            []
          );