当前位置:首页 > React

react 简单table实现

2026-01-26 19:49:56React

基础表格实现

使用 React 实现简单表格可以通过原生 HTML 的 <table> 标签结合动态数据渲染完成。以下是一个基础示例,展示如何通过数组数据动态生成表格内容:

import React from 'react';

const SimpleTable = ({ data }) => {
  return (
    <table border="1">
      <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>
  );
};

// 使用示例
const App = () => {
  const tableData = [
    { id: 1, name: 'Alice', age: 25 },
    { id: 2, name: 'Bob', age: 30 },
    { id: 3, name: 'Charlie', age: 28 },
  ];

  return <SimpleTable data={tableData} />;
};

动态表头扩展

若表头需要动态生成,可以通过遍历对象的键来渲染:

const DynamicHeaderTable = ({ data }) => {
  if (data.length === 0) return null;
  const headers = Object.keys(data[0]);

  return (
    <table border="1">
      <thead>
        <tr>
          {headers.map((header) => (
            <th key={header}>{header.toUpperCase()}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.map((row, index) => (
          <tr key={index}>
            {headers.map((header) => (
              <td key={`${index}-${header}`}>{row[header]}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
};

添加样式与交互

通过 CSS 或库(如 styled-components)美化表格,并增加交互功能(如排序):

import styled from 'styled-components';

const StyledTable = styled.table`
  width: 100%;
  border-collapse: collapse;
  th, td {
    padding: 8px;
    text-align: left;
    border-bottom: 1px solid #ddd;
  }
  tr:hover {
    background-color: #f5f5f5;
  }
`;

const SortableTable = ({ data }) => {
  const [sortConfig, setSortConfig] = React.useState({ key: null, direction: 'asc' });

  const sortedData = React.useMemo(() => {
    if (!sortConfig.key) return data;
    return [...data].sort((a, b) => {
      if (a[sortConfig.key] < b[sortConfig.key]) {
        return sortConfig.direction === 'asc' ? -1 : 1;
      }
      if (a[sortConfig.key] > b[sortConfig.key]) {
        return sortConfig.direction === 'asc' ? 1 : -1;
      }
      return 0;
    });
  }, [data, sortConfig]);

  const requestSort = (key) => {
    let direction = 'asc';
    if (sortConfig.key === key && sortConfig.direction === 'asc') {
      direction = 'desc';
    }
    setSortConfig({ key, direction });
  };

  return (
    <StyledTable>
      <thead>
        <tr>
          {Object.keys(data[0]).map((key) => (
            <th key={key} onClick={() => requestSort(key)}>
              {key.toUpperCase()} {sortConfig.key === key ? (sortConfig.direction === 'asc' ? '↑' : '↓') : ''}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {sortedData.map((row, index) => (
          <tr key={index}>
            {Object.values(row).map((value, i) => (
              <td key={i}>{value}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </StyledTable>
  );
};

使用第三方库

对于复杂需求(如分页、过滤),可考虑使用现成库:

  • React Table: 轻量级且高度可定制(文档)。
  • Material-UI Table: 提供 Material Design 风格的预制组件(文档)。

安装示例(React Table):

react 简单table实现

npm install react-table
import { useTable } from 'react-table';

const ReactTableExample = ({ columns, data }) => {
  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({
    columns,
    data,
  });

  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>
  );
};

标签: 简单react
分享给朋友:

相关文章

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 依赖于 Node.js 和 npm(Node Package Manager)。从 Node.js 官网下载并安装最新稳定版本,安装完成后会自动包含 np…

react如何调试

react如何调试

调试 React 应用的方法 使用 React Developer Tools React Developer Tools 是 Chrome 和 Firefox 的浏览器扩展,可以检查组件树、状态和…

react架构如何

react架构如何

React 架构核心概念 React 的架构围绕组件化、虚拟 DOM 和单向数据流设计。组件是构建用户界面的独立模块,分为函数组件和类组件。虚拟 DOM 通过高效的 Diff 算法减少直接操作真实 D…

react如何发音

react如何发音

React的发音 React的正确发音为 /riˈækt/,类似于“ree-akt”。以下是详细说明: 发音分解 第一个音节“Ree”发音类似英文单词“see”中的“ee”音。…

react如何引入

react如何引入

引入React的方法 React可以通过多种方式引入项目,具体取决于项目需求和开发环境。以下是常见的几种方法: 通过CDN引入 在HTML文件中直接通过CDN链接引入React和ReactDOM:…

如何运行react项目

如何运行react项目

运行React项目的步骤 确保已安装Node.js(建议版本12或更高)和npm/yarn。若未安装,可从Node.js官网下载。 全局安装create-react-app脚手架工具(若已安装可跳过…