如何在不使用TypeScript的情况下实现react-table(v8版本)
在非TypeScript React项目中使用React Table v8
React Table v8的核心API本身支持JavaScript,TypeScript示例仅提供类型约束,你可以直接通过以下步骤在纯JS React项目中实现:
1. 安装依赖
直接安装核心包即可,无需额外类型依赖:
npm install @tanstack/react-table # 或使用yarn yarn add @tanstack/react-table
2. 基础表格实现
导入核心函数
import { useReactTable, createColumnHelper } from '@tanstack/react-table';
定义列与数据
无需指定泛型,直接创建列配置和表格数据:
// 创建列助手 const columnHelper = createColumnHelper(); // 定义列配置 const columns = [ columnHelper.accessor('name', { header: '姓名', cell: (info) => info.getValue(), }), columnHelper.accessor('age', { header: '年龄', cell: (info) => info.getValue(), }), columnHelper.accessor('email', { header: '邮箱', cell: (info) => info.getValue(), }), ]; // 示例表格数据 const data = [ { name: '张三', age: 28, email: 'zhangsan@example.com' }, { name: '李四', age: 32, email: 'lisi@example.com' }, { name: '王五', age: 25, email: 'wangwu@example.com' }, ];
渲染表格组件
在React组件中使用useReactTable钩子生成表格实例,再渲染DOM结构:
function BasicTable() { const table = useReactTable({ data, columns, }); return ( <table border="1" cellPadding="8" cellSpacing="0"> <thead> {table.getHeaderGroups().map((headerGroup) => ( <tr key={headerGroup.id}> {headerGroup.headers.map((header) => ( <th key={header.id}> {header.isPlaceholder ? null : header.renderHeader()} </th> ))} </tr> ))} </thead> <tbody> {table.getRowModel().rows.map((row) => ( <tr key={row.id}> {row.getVisibleCells().map((cell) => ( <td key={cell.id}>{cell.renderCell()}</td> ))} </tr> ))} </tbody> </table> ); }
3. 添加常用功能(以排序为例)
React Table v8的插件系统在JS中同样可用,只需导入对应插件函数并配置:
导入排序插件
import { useReactTable, createColumnHelper, getCoreRowModel, getSortedRowModel } from '@tanstack/react-table';
启用排序配置
// 给需要排序的列开启排序功能 const columns = [ columnHelper.accessor('name', { header: '姓名', cell: (info) => info.getValue(), enableSorting: true, // 启用排序 }), columnHelper.accessor('age', { header: '年龄', cell: (info) => info.getValue(), enableSorting: true, }), // ...其他列 ]; // 配置表格实例,添加排序插件 const table = useReactTable({ data, columns, getCoreRowModel: getCoreRowModel(), // 核心数据模型 getSortedRowModel: getSortedRowModel(), // 排序数据模型 });
渲染排序表头
修改表头渲染逻辑,添加排序触发按钮和状态提示:
<th key={header.id} onClick={header.column.getToggleSortingHandler()} style={{ cursor: 'pointer' }} > {header.isPlaceholder ? null : header.renderHeader()} {/* 显示排序状态 */} {header.column.getIsSorted() ? ( header.column.getIsSorted() === 'asc' ? ' ↑' : ' ↓' ) : ''} </th>
4. 额外提示
- 分页、筛选等其他功能的实现逻辑与排序一致:导入对应插件(如
getPaginationRowModel、getFilteredRowModel),配置到表格实例,再添加对应的交互DOM。 - 若需要编辑器代码提示,可通过JSDoc注释为数据添加类型说明,例如:
/** @type {Array<{name: string, age: number, email: string}>} */ const data = [/* ... */];
内容的提问来源于stack exchange,提问作者N_Z
相关产品推荐
相关产品推荐

