我有一个工作正常的 API 项目,包括 Pagination.First、Pagination.Prev、Pagination.Item、Pagination.Next 和 Pagination.Last。
我想在其上添加 Pagination.Ellipsis 但我不知道如何将其插入到我的代码中。
查看分页文档react-bootstrap.github.io
这是我尝试使用分页省略号 sandboxEllipses 实现的示例。
下面是我的代码,也是沙箱代码 https://codesandbox.io/。
Movielist.js
import { React, useState, useEffect } from "react";
import { Col, Card, Row, Pagination } from "react-bootstrap";
import MovieListPagination from "./MovieListPagination";
const MovieList = () => {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// Default current pages and posts
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(4);
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = items.slice(indexOfFirstPost, indexOfLastPost);
// Change page
const paginate = (pageNumber) => setCurrentPage(pageNumber);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
//console.log(result.results);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
}, []);
if (error) {
return Error: {error.message};
} else if (!isLoaded) {
return Loading...;
} else {
return (
<>
{currentPosts.map((item) => (
{item.title}
{item.body}
))}
>
);
}
};
export default MovieList;
MovielistPagination.js
import { React } from "react";
import { Pagination } from "react-bootstrap";
const MovieListPagination = ({
currentPage,
postsPerPage,
totalPosts,
paginate
}) => {
const pageNumbers = [];
const pagesCount = Math.ceil(totalPosts / postsPerPage);
const isCurrentPageFirst = currentPage === 1;
const isCurrentPageLast = currentPage === pagesCount;
for (let i = 1; i <= pagesCount; i++) {
pageNumbers.push(i);
}
return (
<>
paginate(1)} />
paginate(currentPage - 1)}
disabled={isCurrentPageFirst}
/>
{pageNumbers.map((number) => (
{
paginate(number);
}}
>
{number}
))}
paginate(currentPage + 1)}
disabled={isCurrentPageLast}
/>
paginate(pagesCount)} />
>
);
};
export default MovieListPagination;
我尝试了一些解决办法,例如 和 ff 代码...但它不起作用。
// Add ellipses if there are more pages to display
if (pageNumbers[0] > 1) {
pageNumbers.unshift( );
}
if (pageNumbers[pageNumbers.length - 1] < totalPosts) {
pageNumbers.push( );
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
目前我对问题的回答是使用react-paginate。您可以在 codesandbox 上找到我的分叉答案。
我会保留我的问题,也许有人可以帮忙。谢谢!