用途:面向 React 构建无头(headless)、类型安全的数据表格,通过 @tanstack/react-table 提供的 hooks 与列定义渲染可排序、筛选、分页、选择、展开的表格。安装:npm install @tanstack/react-table,要求 React 16.8+,推荐 TypeScript。核心用法:用 createColumnHelper<TData>() 定义 columns,调用 useReactTable({ data, columns, getCoreRowModel: getCoreRowModel() }),渲染时用 flexRender 处理表头与单元格,遍历 getHeaderGroups()、getRowModel().rows,并用 getVisibleCells()。能力:按需导入行模型(getSortedRowModel 排序、getFilteredRowModel 筛选、getPaginationRowModel 分页、getExpandedRowModel 展开、getGroupedRowModel 分组、getFacetedRowModel 等),行模型管道顺序为 Core -> Filtered -> Grouped -> Sorted -> Expanded -> Paginated -> Rendered。受控状态用 state 与 on*Change(如 sorting、columnFilters、pagination);服务端分页用 manualPagination 与 rowCount;行选择用 checkbox 列并配合 getRowId 维持跨刷新稳定 ID。限制与注意:data 与 columns 必须稳定引用(用 useState、useMemo 或组件外定义),否则无限重渲染;渲染单元格用 getVisibleCells() 而非 getAllCells();不要对同一功能同时用 initialState 与 state;启用 manualSorting 等手动模式时不要再导入对应客户端行模型;未提供 getRowId 时行 ID 默认为索引,会影响选择状态。
tanstack-table
前端与建站
更新于 10-16 08:46