[英]How to add active class to the pagination in React
I have a pagination component like this:我有一个这样的分页组件:
import React from "react";
import { Link } from "react-router-dom";
const Pagination = ({ currentPage, postsPerPage, totalPosts, paginate }) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
return (
<nav>
<ul className="pagination">
<li class="page-item">
<Link class="page-link" to={currentPage-1} onClick={() => paginate(currentPage-1)} aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</Link>
</li>
{pageNumbers.map((number) => (
<li key={number} className="page-item">
<Link
onClick={() => paginate(number)}
to={number}
className="page-link"
>
{number}
</Link>
</li>
))}
<li class="page-item">
<Link class="page-link" to={currentPage+1} onClick={() => paginate(currentPage+1)} aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</Link>
</li>
</ul>
</nav>
);
};
export default Pagination;
So, what I want to do is when it is on page 5 for example, I want to add active class to that li so I can figure out on what page I am.所以,我想做的是,例如,当它在第 5 页时,我想向那个 li 添加活动类,这样我就可以弄清楚我在哪个页面上。 Could you give me an advice about it?你能给我一个建议吗?
Thanks谢谢
You cann add calssName active
for currentPage
like this:您不能像这样为currentPage
添加 calssName active
:
<Link
className={`page-link ${currentPage === number ? "active" : ""}`}
>
Instead of using Link, yiou can use NavLink which gives you the isActive property to add activeClassName to the page index in your pagination: yiou 可以使用 NavLink 而不是使用 Link,它为您提供 isActive 属性以将 activeClassName 添加到分页中的页面索引:
<NavLink to={`${yourLinkToPage}`} className={({isActive}) => `someClassName ${isAtive ? activeClassName : ""}`} >LinkName</NavLink>
and you can see the documentation also:您还可以查看文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.