当前位置:首页 > 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} />;
};

动态表头扩展

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

react 简单table实现

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)美化表格,并增加交互功能(如排序):

react 简单table实现

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):

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页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 编写组件代码 在…

react native如何启动

react native如何启动

如何启动 React Native 项目 安装 Node.js 和 npm 确保已安装 Node.js(建议版本 16 或更高)和 npm(Node.js 自带)。可通过以下命令检查版本: nod…

如何生成react代码

如何生成react代码

使用 Create React App 生成项目 安装 Node.js 后,通过命令行工具运行以下命令创建新项目: npx create-react-app my-app cd my-app np…

如何记忆react

如何记忆react

理解核心概念 React的核心概念包括组件、状态(state)、属性(props)、生命周期方法(类组件)和钩子(函数组件)。掌握这些基础概念是记忆React的关键。组件是React应用的构建块,分为…

react如何查

react如何查

React 查询方法 React 提供了多种查询 DOM 元素的方式,以下是几种常见的方法: 使用 ref 通过 useRef 钩子可以获取 DOM 节点的引用,适用于直接操作 DOM 的场景。…

react如何读

react如何读

React 的发音 React 的发音为 /riˈækt/(音标),读作“瑞-艾克特”。其中: “Re” 发音类似英文单词 “read” 的开头部分。 “act” 发音与英文单词 “act” 一致…