当前位置:首页 > React

react 分页实现

2026-01-26 12:39:02React

分页组件实现

使用React实现分页功能通常需要结合状态管理、数据请求和UI渲染。以下是两种常见的实现方式:

基础分页组件

import { useState } from 'react';

function Pagination({ totalItems, itemsPerPage, onPageChange }) {
  const [currentPage, setCurrentPage] = useState(1);
  const totalPages = Math.ceil(totalItems / itemsPerPage);

  const handleClick = (page) => {
    setCurrentPage(page);
    onPageChange(page);
  };

  return (
    <div className="pagination">
      <button 
        disabled={currentPage === 1}
        onClick={() => handleClick(currentPage - 1)}
      >
        Previous
      </button>

      {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
        <button
          key={page}
          onClick={() => handleClick(page)}
          className={currentPage === page ? 'active' : ''}
        >
          {page}
        </button>
      ))}

      <button
        disabled={currentPage === totalPages}
        onClick={() => handleClick(currentPage + 1)}
      >
        Next
      </button>
    </div>
  );
}

API数据分页集成

与后端API集成时,通常需要处理分页参数和响应数据:

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

function DataList() {
  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>
      {/* 渲染数据列表 */}
      <Pagination 
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={setCurrentPage}
      />
    </div>
  );
}

高级分页功能

对于更复杂的分页需求,可以考虑以下增强功能:

react 分页实现

页码范围优化

const getPageNumbers = () => {
  const maxVisiblePages = 5;
  let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;

  if (endPage > totalPages) {
    endPage = totalPages;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }

  return Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);
};

分页样式优化

react 分页实现

.pagination {
  display: flex;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
}

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

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

使用现成库

对于快速实现,可以考虑使用现成的React分页库:

  • react-paginate
  • material-ui pagination
  • antd pagination

安装示例:

npm install react-paginate

使用示例:

import ReactPaginate from 'react-paginate';

function PaginatedItems({ itemsPerPage, items }) {
  const [itemOffset, setItemOffset] = useState(0);
  const endOffset = itemOffset + itemsPerPage;
  const currentItems = items.slice(itemOffset, endOffset);
  const pageCount = Math.ceil(items.length / itemsPerPage);

  const handlePageClick = (event) => {
    const newOffset = (event.selected * itemsPerPage) % items.length;
    setItemOffset(newOffset);
  };

  return (
    <>
      <Items currentItems={currentItems} />
      <ReactPaginate
        breakLabel="..."
        nextLabel="next >"
        onPageChange={handlePageClick}
        pageRangeDisplayed={5}
        pageCount={pageCount}
        previousLabel="< previous"
        renderOnZeroPageCount={null}
      />
    </>
  );
}

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

相关文章

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment 包。确保项目中已安装 moment.js,因为 react-moment 依赖它。 npm install…

如何启动react

如何启动react

安装Node.js 确保系统已安装Node.js(建议使用LTS版本),可通过官网下载并安装。安装完成后,在终端运行以下命令验证版本: node -v npm -v 创建React项目 使用官方工具…

react如何循环

react如何循环

循环渲染列表 在React中循环渲染列表通常使用map方法,这是最常用的方式。通过map可以将数组中的每个元素转换为React元素并渲染到页面上。 const items = ['Apple', '…

typescript react 如何

typescript react 如何

TypeScript 与 React 结合使用的方法 在 React 项目中使用 TypeScript 可以提升代码的可维护性和类型安全性。以下是一些关键步骤和最佳实践: 安装 TypeScript…

react如何通信

react如何通信

React 组件通信方式 React 组件间的通信方式多样,具体选择取决于组件关系和场景需求。以下是常见方法: 父子组件通信 父组件通过 props 向子组件传递数据,子组件通过回调函数通知父组件…

react 如何操作cookie

react 如何操作cookie

安装依赖 在React项目中操作cookie通常需要第三方库的支持,推荐使用js-cookie。通过npm或yarn安装: npm install js-cookie # 或 yarn add js…