当前位置:首页 > React

react 如何分页

2026-02-11 12:25:20React

分页实现方法

在React中实现分页功能通常需要结合状态管理和UI组件。以下是几种常见的方法:

使用useState管理分页状态

import { useState } from 'react';

function PaginatedList({ items }) {
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  const totalPages = Math.ceil(items.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const currentItems = items.slice(startIndex, startIndex + itemsPerPage);

  return (
    <div>
      {currentItems.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
      <div>
        {Array.from({ length: totalPages }, (_, i) => (
          <button 
            key={i + 1}
            onClick={() => setCurrentPage(i + 1)}
            disabled={currentPage === i + 1}
          >
            {i + 1}
          </button>
        ))}
      </div>
    </div>
  );
}

使用第三方分页组件

React有许多优秀的分页组件库,如react-paginate:

import ReactPaginate from 'react-paginate';

function PaginatedComponent({ data }) {
  const [currentPage, setCurrentPage] = useState(0);
  const perPage = 5;
  const pageCount = Math.ceil(data.length / perPage);
  const offset = currentPage * perPage;

  const handlePageClick = ({ selected }) => {
    setCurrentPage(selected);
  };

  return (
    <div>
      {data.slice(offset, offset + perPage).map(item => (
        <div key={item.id}>{item.content}</div>
      ))}
      <ReactPaginate
        previousLabel={'previous'}
        nextLabel={'next'}
        breakLabel={'...'}
        pageCount={pageCount}
        marginPagesDisplayed={2}
        pageRangeDisplayed={5}
        onPageChange={handlePageClick}
        containerClassName={'pagination'}
        activeClassName={'active'}
      />
    </div>
  );
}

服务器端分页

当数据量很大时,建议实现服务器端分页:

import { useState, useEffect } from 'react';
import axios from 'axios';

function ServerPagination() {
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const itemsPerPage = 10;

  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get(
        `/api/items?page=${currentPage}&limit=${itemsPerPage}`
      );
      setData(response.data.items);
      setTotalPages(response.data.totalPages);
    };
    fetchData();
  }, [currentPage]);

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
      <div>
        {Array.from({ length: totalPages }, (_, i) => (
          <button
            key={i + 1}
            onClick={() => setCurrentPage(i + 1)}
          >
            {i + 1}
          </button>
        ))}
      </div>
    </div>
  );
}

分页样式优化

可以添加CSS样式增强分页组件的视觉效果:

react 如何分页

.pagination {
  display: flex;
  list-style: none;
  padding: 0;
}

.pagination li {
  margin: 0 5px;
}

.pagination li a {
  padding: 8px 16px;
  border: 1px solid #ddd;
  cursor: pointer;
}

.pagination li.active a {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

.pagination li.disabled a {
  color: #ddd;
  cursor: not-allowed;
}

性能考虑

对于大型数据集,虚拟滚动可能是比传统分页更好的选择。可以考虑使用react-window或react-virtualized等库实现虚拟滚动,这能显著提升性能。

标签: 分页react
分享给朋友:

相关文章

vue实现选项卡分页

vue实现选项卡分页

Vue实现选项卡分页的方法 使用动态组件切换 通过Vue的<component :is="currentTab">动态加载不同组件,结合v-for循环渲染选项卡标题,点击时切换curre…

react如何使用

react如何使用

React 的基本使用 React 是一个用于构建用户界面的 JavaScript 库,以下是一些核心概念和使用方法。 安装 React 通过 create-react-app 快速搭建 React…

如何生成react代码

如何生成react代码

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

vue 分页 实现

vue 分页 实现

Vue 分页实现方法 使用 Element UI 分页组件 Element UI 提供了现成的分页组件 el-pagination,适合快速集成。需要先安装 Element UI 库。 安装 Ele…

react如何配置

react如何配置

配置React项目的基本步骤 安装Node.js和npm 确保系统已安装Node.js(包含npm)。可通过命令行检查版本: node -v npm -v 创建React项目 使用官方工具Creat…

react如何减少伤病

react如何减少伤病

减少React应用中的性能问题(避免"伤病") 优化React应用性能需要从组件渲染、状态管理和外部依赖等多方面入手。以下是关键优化策略: 使用React.memo进行组件记忆 对函数组件使用Rea…