当前位置:首页 > 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有许多优秀的分页组件库,如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>
  );
}

服务器端分页

react 如何分页

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

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样式增强分页组件的视觉效果:

.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 分页实现方法 基础分页组件实现 创建一个简单的分页组件,包含上一页、下一页和页码按钮。组件接收当前页码、总页数等参数,通过事件通知父组件页码变化。 <template> &l…

如何关闭react

如何关闭react

关闭React应用的步骤 在开发或运行React应用时,可能需要关闭正在运行的开发服务器或停止应用。以下是几种常见情况的处理方法: 停止开发服务器 如果正在使用npm start或yarn star…

react如何折叠

react如何折叠

在 React 中实现折叠功能 使用 useState 管理折叠状态 通过 useState 定义一个状态变量来控制折叠面板的显示与隐藏。例如: const [isCollapsed, setIsC…

react如何减少伤病

react如何减少伤病

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

react如何实现混入

react如何实现混入

在React中实现混入(Mixin)功能可以通过以下几种方式实现,React官方已不推荐使用传统的React.createClass混入方式,但可通过高阶组件或自定义Hook替代。 高阶组件(HOC…

react如何修改值

react如何修改值

修改 React 组件的值 在 React 中修改值通常涉及状态管理。根据组件的类型(类组件或函数组件)和状态管理方式(本地状态或全局状态),方法有所不同。 使用 useState(函数组件) 在函…