当前位置:首页 > 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的表格组件。

react实现表格代码

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

相关文章

vue实现通讯录代码

vue实现通讯录代码

以下是一个基于Vue.js实现的通讯录示例代码,包含联系人列表、搜索和添加功能: 实现步骤 创建Vue组件 <template> <div class="address-…

vue 实现表格单选

vue 实现表格单选

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

用css制作表格

用css制作表格

使用CSS制作表格 CSS可以用来样式化HTML表格,使其更具视觉吸引力和功能性。以下是几种常见的方法: 基础表格样式 通过CSS可以调整表格的边框、间距和颜色: <table>…

怎么制作css表格

怎么制作css表格

使用HTML和CSS创建表格 HTML提供<table>标签用于创建表格结构,CSS用于控制样式。以下是一个基础示例: <table class="styled-table">…

表格tb制作css

表格tb制作css

使用CSS美化HTML表格 通过CSS可以自定义表格样式,使其更美观和符合设计需求。以下是一些常用方法: 基础表格样式 table { width: 100%; border-collap…

如何实现vue表格联动

如何实现vue表格联动

实现 Vue 表格联动的方法 数据绑定与响应式更新 通过 Vue 的响应式特性,将多个表格的数据绑定到同一个数据源或计算属性。当一个表格的数据发生变化时,另一个表格会自动更新。例如: data()…