首页 > 解决方案 > 反应表没有正确排序数字

问题描述

React-table 对小数进行排序,如下所示:

在此处输入图像描述

我的猜测是,虽然我从服务器接收数字,但 react-table 将它们作为文本处理。所以,我像这样修改了访问器:

accessor: d => Number(d.Invoice_Weight).toFixed(2)

但我一直弄错排序。

这是列的代码:

 {
                      Header: () => 
                      <DropDownMenu 
                      header={content[lang].Invoice_Weight}
                      openModal = {this.onOpenSelectColumnsModal}
                      />,
                      id: 'Invoice_Weight',
                      sortable: true,
                      accessor: d => Number(d.Invoice_Weight).toFixed(2),
                      //width: 200,
                      getProps: () => {
                        return {
                          style: {
                            textAlign: 'right'
                          }
                        }
                      },
                      show: Invoice_Weight,
                    },

标签: reactjsreact-table

解决方案


正如其他答案中所建议的那样,问题是toFixed返回一个字符串,因此排序将使用字符串比较来完成。但是,在这种情况下强制返回数字将不起作用,因为这样您将丢失尾随0s,我猜您仍然需要。

另一种解决方案是使用自定义排序:

accessor: d => Number(d.Invoice_Weight).toFixed(2),
sortMethod: (a, b) => Number(a)-Number(b)

您可能想要改进sortMethod以处理 NaN 和 Infinities(如果有的话),但这是一般的想法

您可以使用它来强制字符串返回一个数字,但只能在排序的上下文中,而不影响显示的值


推荐阅读