【问题标题】:Multiple react-table instances on same page同一页面上的多个反应表实例
【发布时间】:2021-07-14 22:52:47
【问题描述】:

我在 NextJS 项目中使用react-table,我想知道如何在同一页面上拥有多个表。一直在挖掘,但没有发现任何关于它的信息。

我已经在页面上有一个实例,我不确定我是否想多了,但我想我可以创建一个 tableInstance2 但是,我将如何告诉第二个表 JSX 使用它第二批数据?

  const tableInstance = useTable({
    columns: COLUMNS,
    data: tableData
  },
  useSortBy);

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = tableInstance;

这是我当前的表格标记:

{tableData.length > 0 && 
  <div className={styles.tableSpace}>
    <table {...getTableProps()} className={styles.table}>
      <thead className={styles.thead}>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()} className={styles.tr}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps(column.getSortByToggleProps())} className={styles.th}>
                {column.render('Header')}
                  {column.Header !== 'Description' && 
                    <span>
                      {column.isSorted ? (column.isSortedDesc ? <FontAwesomeIcon className={styles.faCaretDown} icon={faCaretDown} /> : <FontAwesomeIcon className={styles.faCaretUp} icon={faCaretUp} />) : <FontAwesomeIcon className={styles.faArrowsAltV} icon={faArrowsAltV} />}
                    </span>
                  }
              </th>
            ))}
          </tr>
        ))}
      </thead>

      <tbody {...getTableBodyProps} className={styles.tbody}>
        {rows.map(row => {
          prepareRow(row)
          return (
            <tr {...row.getRowProps()} className={styles.tr}>
              {row.cells.map((cell) => {
                return (
                  <td {...cell.getCellProps()} className={styles.td}>
                    {cell.render('Cell')}
                  </td>
                )
              })}
            </tr>
          )
        })}
      </tbody>
    </table>
  </div>
}

在同一个页面(在同一个文件中)是否有可能超过 1 个? 将不胜感激任何提示。非常感谢!

【问题讨论】:

  • 没有理由不能在一个组件中拥有两个 react-table 表。但是,如果这两个表具有相似的属性,为什么不创建自己的 Table 组件来处理 useTable 钩子,然后让您的父组件呈现两个表?
  • @j-petty 感谢您的评论。它们都有不同的列、不同的数据和一点不同的 JSX 标记。我可能不得不将它们分开,但希望我可以将它们放在同一个文件中。这真的归结为我如何为他们提供各自的 tableInstance。

标签: reactjs react-table react-table-v7


【解决方案1】:

React table 帮助您制作自己的表格组件 - 您已经做到了。您只需要将表格移动到它自己的文件并概括列。

下面是一个通用且可重用的表格示例 - 您可以像 official examples 中的任何一个一样扩展表格组件,以启用分页或排序等功能。 React-table 还希望你 memoize the columns(和数据),所以我将列转换为可重用组件中的备忘录,这样你就不必在每个页面上都有一个表格。

table.js

export const Table = ({ columns, data, noDataComponent, ...rest }) => {
  const tableColumns = useMemo(() => columns, [columns]);
  const { getTableBodyProps, getTableProps, headerGroups, prepareRow, rows } = useTable({ columns: tableColumns, data });

  if (!rows.length) {
    if (noDataComponent) return noDataComponent;
    return <>No data</>;
  }

  return (
    <table {...getTableProps()} {...rest}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>{column.render('Header')}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                const { className, style } = cell.column;
                return (
                  <td {...cell.getCellProps({ className, style })}>
                    {cell.render('Cell')}
                  </td>
                );
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

使用可重用组件在同一页面上的多个表。每个表都可以有自己的数据、列数等 - 它们彼此独立。

const columns = [
  {
    Header: 'Test ID',
    accessor: 'test.id', // use dot notation for nested data
    style: { width: '75px' },
  },
  {
    Header: 'Name',
    accessor: 'name',
  },
  {
    accessor: 'id',
    style: { width: '75px' },
    Cell: ({ cell }) => {
      const { 'test.id': testId, name, id }= cell.row.values; // access other data from the row
      console.log(cell);
      return <>Custom component</> // return any ReactNode like a delete button, icons, transform the value, etc.
    },
  },
];

const TablePage = () => (
  <>
   <Table data={tableData} columns={columns} />
   <Table data={tableData2} columns={columns2} />
  </>
)

【讨论】:

    【解决方案2】:

    如果两个表之间存在合理的重用,您应该考虑实现自己的表组件,该组件包装了useTable 钩子。

    但是,如果您真的想在同一个组件中包含两个表,您可以重命名解构变量,如MDN Example 中所述。这允许您区分两个表的变量。

    查看示例(将变量重命名为适合您应用程序上下文的名称):

    const {
        getTableProps: getFirstTableProps,
        getTableBodyProps: getFirstTableBodyProps,
        headerGroups: firstGeaderGroups,
        rows: firstRows,
        prepareRow: firstPrepareRow
    } = tableInstance;
    

    【讨论】:

      【解决方案3】:

      我非常感谢对此的回复。他们共同引导了我的思考并帮助我找到了最适合我的情况的解决方案。似乎有不同的处理方法,但因为我的表格标记有一些差异,一个有排序功能,另一个没有......我选择不把自己画到角落里,只有 1 个可重复使用的表格组件。

      我想在添加新表时考虑到未来的可维护性和更大的灵活性,我选择为每个表创建一个组件,并且将这两个表作为组件包含在页面上。

      仍然在页面级别检索两个表所需的数据,然后将数据传递到各自的组件中。每个组件中定义了不同的列,不同的表实例也是如此。

      再次感谢您给我选择的那些人。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        相关资源
        最近更新 更多