首页 > 解决方案 > 过滤反应表数据中的格式化数据

问题描述

我想在自定义过滤器中访问格式化以及“未触及”的数据,但我没有成功:

accessor: row => {
    row.ageFormatted = row.age + " yrs";
    return row.age;
},
Cell: row => (
    <div style={{ textAlign: "center" }}>
        {row.original.ageFormatted}
    </div>
),
filterMethod: (filter, row) => {
    return (
        row.age + "" === filter.value ||
        row.ageFormatted.contains(filter.value)
    );
}

从我在沙箱中的代码示例:https ://codesandbox.io/s/react-table-custom-filtering-j90oh(自定义过滤的官方react-table示例的一个分支)。用户应该能够过滤数字或字符串,如“3 y”。

我怎样才能做到这一点?

标签: reactjsreact-table

解决方案


您可以将所有格式化的值计算到 Object on 中componentDidMount,将其保存到状态中,然后使用它而不是每次使用过滤器时都计算它。在此处查看我的工作解决方案:https ://codesandbox.io/s/react-table-custom-filtering-84lxw

另外,你的row.ageFormatted.contains(filter.value)比较是错误的。检查字符串是否包含子字符串的正确方法是.includeshttps ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes


推荐阅读