当前位置:首页 > React

react实现表格代码

2026-01-27 07:10:49React

以下是一个使用React实现表格的完整代码示例,包含基本功能如动态渲染数据、排序和分页:

react实现表格代码

基础表格实现

import React from 'react';

const BasicTable = ({ data }) => {
  return (
    <table>
      <thead>
        <tr>
          {Object.keys(data[0]).map((key) => (
            <th key={key}>{key}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.map((row, index) => (
          <tr key={index}>
            {Object.values(row).map((value, i) => (
              <td key={i}>{value}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
};

带排序功能的表格

import React, { useState } from 'react';

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

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

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

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

带分页的表格

import React, { useState } from 'react';

const PaginatedTable = ({ data, itemsPerPage = 5 }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const totalPages = Math.ceil(data.length / itemsPerPage);

  const currentData = data.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  return (
    <div>
      <table>
        <thead>
          <tr>
            {Object.keys(data[0]).map((key) => (
              <th key={key}>{key}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {currentData.map((row, index) => (
            <tr key={index}>
              {Object.values(row).map((value, i) => (
                <td key={i}>{value}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      <div>
        <button 
          disabled={currentPage === 1}
          onClick={() => setCurrentPage(currentPage - 1)}
        >
          上一页
        </button>
        <span> 第 {currentPage} 页/共 {totalPages} 页 </span>
        <button
          disabled={currentPage === totalPages}
          onClick={() => setCurrentPage(currentPage + 1)}
        >
          下一页
        </button>
      </div>
    </div>
  );
};

使用第三方库react-table

import React from 'react';
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>
  );
};

样式优化建议

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

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

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

tr:hover {
  background-color: #f5f5f5;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
}

这些实现可以根据实际需求进行组合和扩展。对于更复杂的需求,推荐使用专门的表格库如react-table或Material-UI的表格组件。

标签: 表格代码
分享给朋友:

相关文章

vue 实现表格单选

vue 实现表格单选

实现表格单选的方法 在Vue中实现表格单选功能可以通过多种方式完成,以下是几种常见的实现方法: 使用v-model绑定选中项 通过v-model绑定一个变量来记录当前选中的行数据。当用户点击某一行时…

css好看的表格制作

css好看的表格制作

CSS表格美化方法 边框与间距优化 使用border-collapse合并边框,避免双线边框。设置padding增加单元格内边距,提升可读性。 table { border-collapse:…

vue表格实现单选框

vue表格实现单选框

Vue 表格实现单选框的方法 在 Vue 中实现表格单选框功能,可以通过结合 el-table(Element UI)或原生表格与 Vue 的数据绑定特性完成。以下是几种常见实现方式: 使用 Ele…

用css制作表格

用css制作表格

使用CSS制作表格 基础表格结构 HTML中表格由<table>、<tr>(行)、<th>(表头)和<td>(单元格)组成。基础结构如下: <t…

js实现代码雨

js实现代码雨

实现代码雨效果 使用HTML5 Canvas和JavaScript可以轻松实现经典的代码雨效果。以下是完整的实现代码和说明: HTML结构 <!DOCTYPE html> <htm…

vue实现表格界面

vue实现表格界面

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