当前位置:首页 > React

node react 实现表格

2026-01-27 06:41:22React

使用 Node.js 和 React 实现表格

创建 Node.js 后端 API

安装必要的依赖包:

npm init -y
npm install express cors

创建一个简单的 Express 服务器,提供表格数据 API:

const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors());

const data = [
  { id: 1, name: 'John', age: 25 },
  { id: 2, name: 'Jane', age: 30 },
  { id: 3, name: 'Bob', age: 20 }
];

app.get('/api/data', (req, res) => {
  res.json(data);
});

const PORT = 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

创建 React 前端应用

使用 Create React App 初始化项目:

npx create-react-app react-table-app
cd react-table-app
npm install axios

创建表格组件 Table.js

node react 实现表格

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const Table = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios('http://localhost:5000/api/data');
      setData(result.data);
    };
    fetchData();
  }, []);

  return (
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
        {data.map(item => (
          <tr key={item.id}>
            <td>{item.id}</td>
            <td>{item.name}</td>
            <td>{item.age}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default Table;

App.js 中使用表格组件:

import React from 'react';
import Table from './Table';

function App() {
  return (
    <div className="App">
      <h1>React Table Example</h1>
      <Table />
    </div>
  );
}

export default App;

运行应用

启动后端服务器:

node server.js

启动前端应用:

node react 实现表格

npm start

添加表格功能增强

对于更复杂的表格功能,可以安装 react-table 库:

npm install react-table

使用 react-table 实现排序和分页:

import { useTable, useSortBy, usePagination } from 'react-table';

const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    page,
    prepareRow,
    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    state: { pageIndex }
  } = useTable(
    { columns, data },
    useSortBy,
    usePagination
  );

  return (
    <>
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map(headerGroup => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column => (
                <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                  {column.render('Header')}
                  <span>
                    {column.isSorted ? (column.isSortedDesc ? ' ↓' : ' ↑') : ''}
                  </span>
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {page.map(row => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map(cell => (
                  <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                ))}
              </tr>
            );
          })}
        </tbody>
      </table>
      <div className="pagination">
        <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
          {'<<'}
        </button>
        <button onClick={() => previousPage()} disabled={!canPreviousPage}>
          {'<'}
        </button>
        <span>
          Page{' '}
          <strong>
            {pageIndex + 1} of {pageOptions.length}
          </strong>
        </span>
        <button onClick={() => nextPage()} disabled={!canNextPage}>
          {'>'}
        </button>
        <button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
          {'>>'}
        </button>
      </div>
    </>
  );
};

样式优化

添加基本 CSS 样式:

table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
  cursor: pointer;
}

.pagination {
  margin-top: 10px;
}

.pagination button {
  margin: 0 5px;
}

这个实现展示了如何创建一个完整的 Node.js 后端 API 和 React 前端表格应用,包括基本的数据展示、排序和分页功能。可以根据需要进一步扩展功能,如添加筛选、编辑或导出功能。

标签: 表格node
分享给朋友:

相关文章

vue实现表格界面

vue实现表格界面

Vue 实现表格界面的方法 使用 Element UI 的表格组件 Element UI 提供了功能丰富的表格组件,适合快速开发表格界面。安装 Element UI 后,可以直接使用 el-table…

用vue实现表格

用vue实现表格

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以轻松渲染表格数据。准备一个数据数组,在模板中用 v-for 循环渲染。 <template> <tab…

vue实现表格内容

vue实现表格内容

Vue实现表格内容的方法 使用原生HTML表格 在Vue模板中直接使用HTML的<table>标签构建表格结构,通过v-for指令动态渲染数据。 <template> &…

vue实现表格树

vue实现表格树

Vue 实现表格树的方法 使用递归组件实现树形表格 在 Vue 中可以通过递归组件实现树形表格结构。定义一个组件,该组件可以调用自身来渲染子节点。 <template> &l…

vue实现表格计算

vue实现表格计算

Vue 表格计算实现方法 使用计算属性 在 Vue 中可以通过计算属性来实现表格数据的动态计算。计算属性会自动缓存结果,只有当依赖的数据发生变化时才会重新计算。 computed: { tota…

vue实现树形表格

vue实现树形表格

实现树形表格的基本思路 树形表格的实现通常需要递归组件来展示层级数据,并通过展开/折叠功能控制子节点的显示。Vue的组件递归特性非常适合处理这种嵌套结构。 数据结构的准备 树形表格的数据通常是一个嵌…