当前位置:首页 > 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实现表格复选的方法 基础实现 在Vue中实现表格复选功能可以通过v-model绑定复选框的状态,结合v-for循环渲染表格数据。以下是一个基础示例: <template> &l…

使用vue实现表格

使用vue实现表格

使用 Vue 实现表格 在 Vue 中实现表格可以通过多种方式完成,以下是一个基于 Vue 3 的示例,展示如何动态渲染表格数据并支持基础功能(如排序、筛选)。 基础表格实现 通过 v-for 循环…

h5实现表格样式

h5实现表格样式

实现H5表格样式的方法 使用HTML和CSS创建基础表格 在HTML中,表格通过<table>标签定义,配合<tr>(行)、<td>(单元格)和<th>…

网页表格制作css代码

网页表格制作css代码

基础表格样式 使用CSS为HTML表格添加基础样式,包括边框、间距和背景色: table { width: 100%; border-collapse: collapse; margin…

vue实现表格透明

vue实现表格透明

实现表格透明的方法 在Vue中实现表格透明效果,可以通过CSS样式调整表格的背景透明度。以下是几种常见的方法: 设置表格背景透明度 通过CSS的background-color属性配合rgba()…

vue实现多级表格

vue实现多级表格

Vue 实现多级表格的方法 使用递归组件实现多级表格 递归组件是处理嵌套数据的理想方式,特别适合展示树形结构的数据。 <template> <table> <…