当前位置:首页 > React

react table 官方实现

2026-01-27 06:37:06React

React Table 官方实现

React Table 是一个轻量级、无头(headless)的 React 表格库,提供高度可定制化的表格功能。以下是其核心实现方式和关键特性:

安装 React Table

通过 npm 或 yarn 安装最新版本的 React Table:

react table 官方实现

npm install @tanstack/react-table
# 或
yarn add @tanstack/react-table

基础表格实现

以下是一个简单的表格实现示例,展示如何定义列和数据:

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>

官方资源

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

相关文章

react native如何启动

react native如何启动

如何启动 React Native 项目 安装 Node.js 和 npm 确保已安装 Node.js(建议版本 16 或更高)和 npm(Node.js 自带)。可通过以下命令检查版本: node…

如何下载react

如何下载react

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

react如何encode

react如何encode

React 中编码的实现方式 在 React 中,编码通常涉及对 URL、HTML 实体或特殊字符的处理。以下是几种常见的编码方法: 使用 encodeURIComponent 进行 URL 编码…

react如何安装

react如何安装

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

react如何启动

react如何启动

启动 React 项目的步骤 确保已安装 Node.js React 需要 Node.js 环境运行,建议安装最新稳定版(LTS)。可通过以下命令检查是否已安装: node -v npm -v…

react如何遍历树

react如何遍历树

遍历树结构的常用方法 在React中遍历树结构通常采用递归或迭代的方式。树结构可以是组件树、DOM树或自定义的数据结构。以下是几种常见的实现方法。 递归组件遍历 使用递归组件可以直观地渲染树形结构。…