You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无Node.js环境下的Django应用中使用React-Table?

解决方法

通过unpkg引入的UMD格式react-table会自动将所有API挂载到浏览器window全局对象下,无需使用ES Module的import语法,按以下步骤调整即可:

  1. 确认依赖引入顺序
    你需要先在HTML中引入react、react-dom的UMD包,再引入react-table的UMD包,顺序错误会导致加载异常:
<!-- 先引入React相关依赖 -->
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<!-- 再引入react-table -->
<script src="https://unpkg.com/react-table@7.8.0/dist/react-table.umd.min.js"></script>
  1. 从全局对象获取API
    所有官方教程中通过import导入的方法,都可以从全局ReactTable对象中解构获取,比如你需要的useTable:
// 替代 import { useTable } from 'react-table'
const { useTable } = ReactTable;

// 如果需要其他拓展钩子,比如排序、筛选,同样从全局对象解构
// const { useTable, useSortBy, useFilters } = ReactTable;

后续的表格渲染逻辑和官方教程完全一致,不需要修改其他代码,示例实现如下:

const columns = [
  { Header: 'ID', accessor: 'id' },
  { Header: '名称', accessor: 'name' }
];

const data = [
  { id: 1, name: '示例数据1' },
  { id: 2, name: '示例数据2' }
];

function MyTable() {
  const tableInstance = useTable({ columns, data });
  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = tableInstance;

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render('Header')}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => <td {...cell.getCellProps()}>{cell.render('Cell')}</td>)}
            </tr>
          )
        })}
      </tbody>
    </table>
  )
}

如果你使用的是v8版本的@tanstack/react-table,全局挂载的对象名为TanStackReactTable,对应获取方法为const { useReactTable } = TanStackReactTable即可。

内容的提问来源于stack exchange,提问作者Scott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:21:02