如何过滤 React Table 对象数组内的值?

问题描述 投票:0回答:2

我正在使用 React Table,最近我遇到了一个问题,无法在我的列数据中搜索嵌套的对象数组!这是我到目前为止的代码。

    {
            Header: "competitors",
            accessor: "competitors",
            Cell: ({ cell }: { cell: CellProps<TableInstance> }) => (
              <div className="flex flex-wrap gap-y-1 items-center">
                {cell.value.map((competitor: Competitor, i: number) => {
                  return (
                    <div key={i}>
                      <span
                        key={i}
                        className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 mx-1"
                      >
                        {competitor.name}
                      </span>
                    </div>
                  );
                })}

基本上,competitors是一个对象数组,在单元格中,我将值更改为其名称。帮忙看看谢谢! :)

reactjs react-table react-table-v7
2个回答
2
投票

我可以通过使用自定义访问器来解决这个问题。该解决方案将数据从对象数组更改为字符串数组,从而使我的全局过滤器能够工作。我希望这对某人有帮助!

   {
            Header: "Competitors",
            // This is a custom accessor to get the string, name. Mainly for the search.
            accessor: (data: { competitors: Competitor[] }) => {
              const output: string[] = [];
              data.competitors.map((c) => {
                return output.push(c.name);
              });
              return output;
            },
            Cell: ({ cell }: { cell: CellProps<TableInstance> }) => {
              return (
                <div className="flex flex-wrap gap-y-1 items-center">
                  {cell.value.map((name: string, i: number) => {
                    return (
                      <div key={i}>
                        <span
                          key={i}
                          className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 mx-1"
                        >
                          {name}
                        </span>
                      </div>
                    );
                  })}

                  <MiniPlusButton onClick={() => console.log("asdasd")} />
                </div>
              );
            },
          },

0
投票

其实你不需要改变

accessor
。编写自定义过滤器功能需要所有这些,您可以在那里 grub 整个对象并编写任何类型的查找条件。 f.e.

const orderItemsFilter: FilterFn<any> = (row, columnId, value, addMeta) 
=> {
  // Rank the item
  const itemRank = rankItem(
    row.original.order_items
      .map((item: OrderItemType) => item.product_name)
      .join(" "),
    value,
  );

  // Store the itemRank info
  addMeta({
    itemRank,
  });

  // Return if the item should be filtered in/out
  return itemRank.passed;
};
© www.soinside.com 2019 - 2024. All rights reserved.