【问题标题】:Change column header name dynamically in React Table在 React Table 中动态更改列标题名称
【发布时间】:2021-09-17 07:37:03
【问题描述】:

我在仪表板项目中使用 React Table。我想在每个选项卡单击时更改 React Table 列标题名称。我将名称状态作为 React 表中的道具传递,但标题文本并未根据道具发生变化。这可以更改其中的列标题吗?

下面是 react table 组件的代码,其中 tabName 是我作为 props 传递的状态,它没有改变。

const BreakdownTable = ({ tabName }) => {
  // console.log(tabName);
  const data = React.useMemo(
    () => [
      {
        col1: "com.gumlet.limited-videoPlay",
        col2: "100",
        col3: "1.3k",
      },
    ],
    []
  );

  const columns = React.useMemo(
    () => [
      {
        Header: tabName,
        accessor: "col1",
      },
      {
        Header: "Unique Views",
        accessor: "col2",
      },
      {
        Header: "Total Views",
        accessor: "col3",
      },
    ],
    []
  );

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    // rows,
    prepareRow,
    page,
    canPreviousPage,
    canNextPage,
    pageOptions,
    // pageCount,
    gotoPage,
    nextPage,
    // previousPage,
    setPageSize,
    pageSize,
    state,
    setGlobalFilter,
  } = useTable(
    {
      columns,
      data,
      initialState: { pageSize: 15 },
    },
    useGlobalFilter,
    useSortBy,
    usePagination
  );

  const { globalFilter } = state;

【问题讨论】:

  • 尝试删除列函数上的 use.Memo。以及在列函数中将 tabname 作为参数传递
  • @SachinVishwakarma 删除 use.Memo .. 并在将 tabname 作为参数传递时显示渲染错误后现在不会渲染标题...!!!

标签: javascript reactjs react-table


【解决方案1】:

您可以尝试制作这样的列,一个简单的纯 JavaScript 数组吗?这将有助于确定问题是否与 useMemo 功能有关。

const columns = [
  {
    Header: tabName,
    accessor: "col1",
  },
  {
    Header: "Unique Views",
    accessor: "col2",
  },
  {
    Header: "Total Views",
    accessor: "col3",
  },
]

【讨论】:

  • 不工作。显示错误:超过最大更新深度。当组件在 react 钩子中重复调用 setState 时,可能会发生这种情况。
  • 你能把你的代码sn-p上传到codesandbox.io网站吗?这将有助于确定根本原因。
  • codesandbox.io/s/spring-cloud-iymd0?file=/src/App.js 这是链接。刚刚添加了 2 个文件。你可以检查...!!
猜你喜欢
  • 2020-09-29
  • 2018-12-27
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
相关资源
最近更新 更多