如何用react做分页
使用 React 实现分页功能
分页是 Web 开发中常见的需求,React 可以通过状态管理和组件化轻松实现分页功能。以下是实现分页的几种方法。
基础分页实现
-
定义状态
使用useState存储当前页码和每页数据量:const [currentPage, setCurrentPage] = useState(1); const [itemsPerPage] = useState(10); -
计算分页数据
根据当前页码和每页数据量,截取当前页的数据:const indexOfLastItem = currentPage * itemsPerPage; const indexOfFirstItem = indexOfLastItem - itemsPerPage; const currentItems = data.slice(indexOfFirstItem, indexOfLastItem); -
渲染分页按钮
根据总数据量和每页数据量计算总页数,并渲染分页按钮:const pageNumbers = []; for (let i = 1; i <= Math.ceil(data.length / itemsPerPage); i++) { pageNumbers.push(i); } return ( <div> {currentItems.map(item => ( <div key={item.id}>{item.name}</div> ))} <div> {pageNumbers.map(number => ( <button key={number} onClick={() => setCurrentPage(number)}> {number} </button> ))} </div> </div> );
优化分页组件
-
封装分页逻辑
将分页逻辑封装为自定义 HookusePagination:
function usePagination(data, itemsPerPage) { const [currentPage, setCurrentPage] = useState(1); const maxPage = Math.ceil(data.length / itemsPerPage); function currentData() { const start = (currentPage - 1) * itemsPerPage; const end = start + itemsPerPage; return data.slice(start, end); } return { currentPage, maxPage, currentData, setCurrentPage }; } -
使用封装后的 Hook
在组件中使用usePagination:const { currentPage, maxPage, currentData, setCurrentPage } = usePagination(data, 10); return ( <div> {currentData().map(item => ( <div key={item.id}>{item.name}</div> ))} <Pagination currentPage={currentPage} maxPage={maxPage} onPageChange={setCurrentPage} /> </div> ); -
分页组件
创建一个可复用的Pagination组件:function Pagination({ currentPage, maxPage, onPageChange }) { return ( <div> <button disabled={currentPage === 1} onClick={() => onPageChange(currentPage - 1)}> Previous </button> <span>{currentPage}</span> <button disabled={currentPage === maxPage} onClick={() => onPageChange(currentPage + 1)}> Next </button> </div> ); }
高级分页功能
-
动态分页按钮
只显示当前页附近的页码,避免按钮过多:
function getPageNumbers(currentPage, maxPage) { const pages = []; const start = Math.max(1, currentPage - 2); const end = Math.min(maxPage, currentPage + 2); for (let i = start; i <= end; i++) { pages.push(i); } return pages; } -
跳转到指定页
添加输入框支持跳转到指定页:function handleJumpToPage(e) { const page = parseInt(e.target.value); if (page >= 1 && page <= maxPage) { onPageChange(page); } } return ( <div> <input type="number" min="1" max={maxPage} onChange={handleJumpToPage} /> </div> ); -
分页样式优化
使用 CSS 或 UI 库(如 Material-UI)美化分页组件:import { Pagination as MuiPagination } from '@mui/material'; function Pagination({ currentPage, maxPage, onPageChange }) { return ( <MuiPagination count={maxPage} page={currentPage} onChange={(_, page) => onPageChange(page)} /> ); }
服务器端分页
-
API 请求分页数据
从服务器获取分页数据,而非在前端分页:async function fetchData(page, limit) { const response = await fetch(`/api/data?page=${page}&limit=${limit}`); return response.json(); } -
管理分页状态
使用useEffect监听页码变化并请求数据:useEffect(() => { fetchData(currentPage, itemsPerPage).then(data => setData(data)); }, [currentPage]);
通过以上方法,可以实现灵活且高效的分页功能,适用于各种 React 应用场景。






