ReactJS动态分页页码显示调整技术求助
动态分页导航栏修改方案
不用修改numberOfPages变量(它负责计算总页数,是必要的),核心是替换生成页码列表的逻辑,让导航栏只显示当前页前后各2个页码(共5个),同时适配首尾边界情况。
修改后的完整NewsRow组件代码
function NewsRow(props) { const [posts, setPosts] = useState([]) useEffect(() => { const fetchAllPosts = async () => { try { const res = await axios.get("/api") setPosts(res?.data); } catch (error) { console.log(error) } } fetchAllPosts() }, [posts.length]) //save new entries when adding new post on site const saveNewEntryHandler = (enteredData) => setPosts(prevPosts => [enteredData, ...prevPosts]) //PAGINATION const [currentPage, setCurrentPage] = useState(1) const recordsPerPage = 4 const numberOfPages = Math.ceil(posts.length / recordsPerPage) const lastIndex = currentPage * recordsPerPage const firstIndex = lastIndex - recordsPerPage const paginatedPosts = posts.slice(firstIndex, lastIndex) // --- 新增动态页码逻辑 --- const pagesToShow = 5; // 固定显示5个页码 let startPage = 1; let endPage = numberOfPages; if (numberOfPages > pagesToShow) { const halfPages = Math.floor(pagesToShow / 2); startPage = currentPage - halfPages; endPage = currentPage + halfPages; // 左边界处理:当前页太靠前时,从第1页开始显示5个 if (startPage < 1) { startPage = 1; endPage = pagesToShow; } // 右边界处理:当前页太靠后时,到最后一页结束显示5个 if (endPage > numberOfPages) { endPage = numberOfPages; startPage = numberOfPages - pagesToShow + 1; } } // 生成要显示的页码数组 const numbers = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i); // --- 动态页码逻辑结束 --- const prevPage = () => { if (currentPage !== 1) setCurrentPage(currentPage - 1) } const changeCurrentPage = (id) => setCurrentPage(id) const nextPage = () => { if (currentPage !== numberOfPages) setCurrentPage(currentPage + 1) } return ( <div className={styles.content_column} > <ImageCarousel /> <Welcome /> <NewsInput onSaveNewEntry={saveNewEntryHandler} fullList={posts} /> {paginatedPosts.map((object) => ( <NewsCard key={object.id} id={object.id} title={object.title} date={object.date} description={object.description} image={object.img} /> ))} <Pagination> <PaginationItem className={'paginationItemStyle'}> <PaginationLink onClick={prevPage}>Prev</PaginationLink> </PaginationItem> {numbers.map((i, key) => ( <PaginationItem key={key} className={'paginationItemStyle'} active={currentPage === i }> <PaginationLink onClick={() => changeCurrentPage(i)}> {i} </PaginationLink> </PaginationItem> ))} <PaginationItem className={'paginationItemStyle'}> <PaginationLink onClick={nextPage}>Next</PaginationLink> </PaginationItem> </Pagination> </div> ) } export default NewsRow
逻辑说明
- 当总页数≤5时,直接显示所有页码,避免出现空白
- 总页数>5时:
- 当前页为1时,自动显示「Prev 1 2 3 4 5 Next」
- 当前页为5时,自动显示「Prev 3 4 5 6 7 Next」
- 当前页接近最后一页(比如总页数17,当前页16),自动显示「Prev 13 14 15 16 17 Next」
- 原有的「Prev」「Next」按钮逻辑完全保留,点击后会自动更新显示的页码范围
内容的提问来源于stack exchange,提问作者enimox
相关产品推荐
相关产品推荐

