react如何封装usetable
封装 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 项目,可以添加类型定义以提高代码健壮性:

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
);
};






