如何在 React-Table.js 中隐藏值为 null 的列?

How can I hide columns whose value is null in React-Table.js?

我有一个正在运行的 React Table,其中包含用于查看马拉松数据的列。然而,半程马拉松使用除了 2 以外的所有相同的列。如果我的数据有一个列 null,我如何动态地告诉 React-Table 隐藏它?这是 Columns 数组中的示例列:

{
    id: "time_35k",
    Header: "35k",
    className: "hide-mobile",
    headerClassName: "hide-mobile",
    style: {
      textAlign: "center"
    },
    show: true,
    accessor: runner => formatTime(runner.time_35k),
    getProps: (state, rowInfo, column) => {
      if (state.value === null) {
        newColumn.show = false;
        newColumn.style.display = "none";
        newColumn.headerStyle.display = "none";
        return {
          style: {
            display: "none"
          },
          headerStyle: {
            display: "none"
          }
        };
      }
    }
  },

这是一个半程马拉松数据对象示例:

{
  "place": 1,
  "name": "Keith Meyer",
  "age": 22,
  "sex_place": 1,
  "sex": "M",
  "rank": 2,
  "time_5k": 987,
  "rank_5k": 1,
  "time_10k": 1976,
  "rank_10k": 1,
  "time_15k": 2981,
  "time_35k": null, // TODO: hide this table column
  "time": 4202,
  "pace": 321,
  "city": "Edwardsville",
  "state": "IL",
  "bib_number": 5011,
  "link": "http://www.youtube.com/watch?v=bkirVvr6acU&t=8s"
}

尝试将列信息中的显示选项设置为基于您的数据,而不仅仅是真实的。例如

{
    id: "time_35k",
    Header: "35k",
    className: "hide-mobile",
    headerClassName: "hide-mobile",
    style: {
      textAlign: "center"
    },
    show: data.columnName,
    accessor: runner => formatTime(runner.time_35k),
    getProps: (state, rowInfo, column) => {
      if (state.value === null) {
        newColumn.show = false;
        newColumn.style.display = "none";
        newColumn.headerStyle.display = "none";
        return {
          style: {
            display: "none"
          },
          headerStyle: {
            display: "none"
          }
        };
      }
    }
  },

如果 data.columnName 为空,它将是假的,您的列应该隐藏。

对于那些想知道为什么这不起作用的人:show 已弃用。请改用 initialstate.hiddenColumns

检查: https://github.com/tannerlinsley/react-table/issues/1804

我用这个选项解决了这个问题:

//...code definition table here
} = useTable(
    {
      columns,
      data,
      initialState: { 
        pageIndex: 0,
        hiddenColumns: ['id'].  //use property option, in columns define id name "id"
      },
    },
    usePagination
  );

我也有与@Trenton 类似的需求。我想隐藏数据为空的列。这是我的解决方案。 :D

    React.useEffect(() => {
    // for each column who's data is null, hide that column.

    let emptyColumns = [];

    _.forEach(data[0], function(value, key) {
      if (value === "") emptyColumns.push(key);
    });

    emptyColumns.push("parentEmailAddress");

    setHiddenColumns(emptyColumns);
  }, [setHiddenColumns, columns]);

经过多天的搜索以查看是否有一个完整的惰性函数可以执行此操作,我发现除了 setHiddenColumns (docs here) 之外没有其他函数。 我最终得到了我认为大多数人会做的事情,只是遍历对象以找到空值,并将该键添加到我传递给 setHiddenColumns 的数组 emptyColumns 中。工作完成:)