React中如何基于元素数量实现每页固定9张图的分页功能
React项目下固定每页9张的图片分页实现方案
核心实现逻辑
- 固定每页展示数量为9,匹配3行3列的网格布局规则
- 引入当前页码的状态管理,替代静态写死的分页参数
- 对全量图片数组做切片处理,仅渲染当前页码对应的图片片段,避免全量渲染的性能损耗
- 分页组件与页码状态双向绑定,点击翻页时自动触发切片计算与视图更新
具体实现调整
- 定义固定常量
在组件外层定义每页固定展示数:const PAGE_SIZE = 9; - 引入页码状态
在组件内部添加状态声明,跟踪当前选中的页码:const [currentPage, setCurrentPage] = useState(1); - 计算当前页的渲染切片
基于当前页码、每页数量计算数组切片的起止索引,截取需要渲染的图片列表:// 计算当前页的起始索引 const startIndex = (currentPage - 1) * PAGE_SIZE; // 计算当前页的结束索引 const endIndex = startIndex + PAGE_SIZE; // 截取当前页需要渲染的图片 const currentRenderImages = data.slice(startIndex, endIndex); // 计算总页数,替代写死的分页count值 const totalPageCount = Math.ceil(data.length / PAGE_SIZE); - 替换视图渲染逻辑
把原来全量遍历data的渲染逻辑,改成遍历截取出的currentRenderImages即可。原布局中Grid item xs={4}的设置,在12栅格体系下单行固定排布3个元素,9个元素刚好组成3行3列的规整网格,无需额外调整布局样式。 - 绑定分页组件的交互事件
给分页组件补充count、page、onChange属性,实现翻页时的状态更新:<Pagination count={totalPageCount} page={currentPage} onChange={(_, page) => setCurrentPage(page)} />
调整后完整可运行代码
import React, { useState } from 'react'; import { Grid, Pagination } from '@mui/material'; import { makeStyles } from '@mui/styles'; const data = [ { img: "https://cdn.pixabay.com/photo/2013/07/21/13/00/rose-165819__340.jpg" }, // 保留全量18条图片数据,与原有数组保持一致 { img: "https://cdn.pixabay.com/photo/2013/07/21/13/00/rose-165819__340.jpg" } ]; // 固定每页展示9张 const PAGE_SIZE = 9; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1 }, paper: { padding: theme.spacing(1), textAlign: "center", color: theme.palette.text.secondary } })); const useStyles3 = makeStyles((theme) => ({ root: { "& > *": { marginTop: theme.spacing(2) } } })); export default function BasicPagination() { const classes3 = useStyles3(); const classes = useStyles(); // 当前页码状态,默认从第一页开始 const [currentPage, setCurrentPage] = useState(1); // 计算当前页需要渲染的图片切片 const startIndex = (currentPage - 1) * PAGE_SIZE; const endIndex = startIndex + PAGE_SIZE; const currentRenderImages = data.slice(startIndex, endIndex); // 计算总页数 const totalPageCount = Math.ceil(data.length / PAGE_SIZE); return ( <> <div className={classes.root}> <Grid container spacing={1}> <Grid container item xs={12} spacing={4}> {/* 仅渲染当前页的图片,不再全量遍历数组 */} {currentRenderImages.map((dataNew, index) => ( <Grid item xs={4} key={index}> <img src={dataNew.img} height="30px" alt="gallery item" /> </Grid> ))} </Grid> </Grid> </div> <div className={classes3.root}> <Pagination count={totalPageCount} page={currentPage} onChange={(_, page) => setCurrentPage(page)} /> </div> </> ); }
实现效果说明
- 当图片总数量为18张时,自动计算得到总页数为2页,第一页展示前9张、第二页展示后9张,完全匹配每页9张的规则
- 3行3列的网格布局由原有栅格配置自动实现,单页9个图片项无额外布局错位
- 全量数据仅在组件挂载时加载,翻页时仅做数组切片,无额外的重复渲染开销
内容的提问来源于stack exchange,提问作者Pranav
相关产品推荐
相关产品推荐

