当前位置:首页 > React

react table 官方实现

2026-01-27 06:37:06React

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

分页控制

添加分页控件到表格:

react table 官方实现

<div>
  <button onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()}>
    Previous
  </button>
  <button onClick={() => table.nextPage()} disabled={!table.getCanNextPage()}>
    Next
  </button>
</div>

官方资源

标签: 官方react
分享给朋友:

相关文章

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 依赖于 Node.js 和 npm(Node Package Manager)。从 Node.js 官网下载并安装最新稳定版本,安装完成后会自动包含 np…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

如何同步react

如何同步react

同步React组件状态的方法 使用useState和useEffect钩子组合可以同步React组件的状态。useState用于声明状态变量,useEffect用于监听状态变化并执行副作用。 imp…

react如何安装

react如何安装

安装React的步骤 确保已安装Node.js(建议版本12或更高),可通过以下命令检查版本: node -v npm -v 使用Create React App快速搭建项目(推荐): npx c…

react如何下载

react如何下载

安装 React 的步骤 通过 npm 或 yarn 安装 React,确保已安装 Node.js(版本建议 ≥ 14.0.0)。打开终端或命令行工具,运行以下命令: npx create-reac…

react如何调度

react如何调度

React 调度机制概述 React 的调度机制通过 Fiber 架构 和 Scheduler 模块实现任务优先级管理与时间切片(Time Slicing),确保高优先级更新(如用户交互)能快速响应,…