当前位置:首页 > React

react如何封装usetable

2026-03-31 02:38:48React

封装 useTable 的自定义 Hook

封装 useTable 可以简化表格组件的逻辑,集中管理分页、排序、筛选等状态。以下是一个基于 react-table 或类似库的封装示例:

import { useMemo } from 'react';
import { useTable, useSortBy, usePagination } from 'react-table';

const useCustomTable = ({ columns, data, initialState = {} }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    page,
    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    setPageSize,
    state: { pageIndex, pageSize, sortBy }
  } = useTable(
    {
      columns,
      data,
      initialState: {
        pageIndex: 0,
        pageSize: 10,
        ...initialState
      }
    },
    useSortBy,
    usePagination
  );

  return {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    page,
    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    setPageSize,
    pageIndex,
    pageSize,
    sortBy
  };
};

使用封装后的 Hook

在组件中直接调用封装好的 Hook,传入必要的参数即可:

import useCustomTable from './useCustomTable';

const TableComponent = ({ data }) => {
  const columns = useMemo(
    () => [
      { Header: 'ID', accessor: 'id' },
      { Header: 'Name', accessor: 'name' }
    ],
    []
  );

  const tableInstance = useCustomTable({ columns, data });

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

扩展功能

如果需要支持更多功能(如筛选、行选择等),可以通过添加插件的方式扩展:

import { useTable, useSortBy, usePagination, useFilters, useRowSelect } from 'react-table';

const useEnhancedTable = ({ columns, data }) => {
  const instance = useTable(
    {
      columns,
      data
    },
    useFilters,
    useSortBy,
    usePagination,
    useRowSelect
  );

  return instance;
};

类型支持(TypeScript)

对于 TypeScript 项目,可以添加类型定义以提高代码健壮性:

react如何封装usetable

import { Column, useTable, TableInstance, UseSortByInstanceProps } from 'react-table';

interface CustomTableOptions<D extends object> {
  columns: Column<D>[];
  data: D[];
  initialState?: Partial<TableState<D>>;
}

const useCustomTable = <D extends object>({
  columns,
  data,
  initialState
}: CustomTableOptions<D>): TableInstance<D> & UseSortByInstanceProps<D> => {
  return useTable(
    { columns, data, initialState },
    useSortBy,
    usePagination
  );
};

标签: reactusetable
分享给朋友:

相关文章

react如何开发组件

react如何开发组件

React 组件开发基础 React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。 函数组件示例: function Gree…

如何配置react

如何配置react

配置React项目的步骤 安装Node.js和npm 确保系统已安装Node.js(包含npm)。可通过官网下载并安装最新版本。安装完成后,运行以下命令验证版本: node -v npm -v 创建…

如何构建react

如何构建react

构建 React 项目的步骤 安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过命令行验证: node -v npm -v 使用 Create React Ap…

如何调试react

如何调试react

调试 React 应用的方法 使用 React Developer Tools 安装浏览器扩展(Chrome/Firefox),通过组件树查看组件状态、props 和 hooks。支持实时编辑 pro…

react native如何

react native如何

React Native 基础知识 React Native 是一个由 Facebook 开发的框架,用于使用 JavaScript 和 React 构建跨平台移动应用。它允许开发者编写一次代码,同时…

odyssey react 如何

odyssey react 如何

Odyssey React 是耐克推出的一款跑鞋系列,以其轻量化设计和React泡沫缓震技术著称。以下是关于该系列鞋款的主要特点和使用建议: 核心特点 React泡沫中底提供出色的能量回馈和缓震效果…