react table 官方实现
React Table 官方实现
React Table 是一个轻量级、无头(headless)的 React 表格库,提供高度可定制化的表格功能。以下是其核心实现方式和关键特性:
安装 React Table
通过 npm 或 yarn 安装最新版本的 React Table:
npm install @tanstack/react-table
# 或
yarn add @tanstack/react-table
基础表格实现
以下是一个简单的表格实现示例,展示如何定义列和数据:
import { useReactTable, getCoreRowModel } from '@tanstack/react-table';
const columns = [
{
header: 'Name',
accessorKey: 'name',
},
{
header: 'Age',
accessorKey: 'age',
},
];
const data = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
];
function Table() {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<table>
<thead>
{table.getHeaderGroups().map(headerGroup => (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => (
<th key={header.id}>
{header.column.columnDef.header}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map(row => (
<tr key={row.id}>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>
{cell.getValue()}
</td>
))}
</tr>
))}
</tbody>
</table>
);
}
核心特性
- 无头设计:不强制使用特定 UI 组件,允许完全自定义表格渲染。
- 高性能:支持虚拟滚动和大数据量渲染优化。
- 插件系统:通过插件扩展功能(排序、分页、过滤等)。
- TypeScript 支持:完全使用 TypeScript 编写,提供类型安全。
常用插件
通过插件扩展表格功能,例如排序和分页:
import {
useReactTable,
getCoreRowModel,
getSortedRowModel,
getPaginationRowModel,
} from '@tanstack/react-table';
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
});
分页控制
添加分页控件到表格:
<div>
<button onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()}>
Previous
</button>
<button onClick={() => table.nextPage()} disabled={!table.getCanNextPage()}>
Next
</button>
</div>
官方资源







