React-table 像这样对小数进行排序:
我的猜测是,虽然我从服务器接收数字,但 react 表将它们作为文本处理。所以,我像这样修改了访问器:
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,
},
最佳答案
正如其他答案中所建议的,问题是 toFixed
返回一个字符串,因此将使用字符串比较来完成排序。但是,在这种情况下,强制返回数字将不起作用,因为您将丢失尾随 0
,我猜您仍然需要它。
另一种解决方案是使用自定义排序:
accessor: d => Number(d.Invoice_Weight).toFixed(2),
sortMethod: (a, b) => Number(a)-Number(b)
您可能想要改进 sortMethod
来处理 NaN 和无穷大(如果有的话),但这就是一般想法
您可以使用它将字符串强制返回数字,但仅限在排序的情况下,而不影响显示的值
关于reactjs - React Table 无法正确排序数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56705115/