You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React分页按钮当前页高亮状态保持问题求助

解决React分页按钮持久高亮问题

你当前使用的:active伪类仅在按钮被点击的瞬间生效,松开鼠标后样式就会恢复默认。要实现分页按钮的持久选中高亮,需要通过React状态跟踪当前页码,再动态给对应按钮添加专属激活类。

步骤1:添加状态跟踪当前页码

在你的分页组件中,添加状态来记录当前选中的页码(假设初始页码为1):

import { useState } from 'react';

// 组件内部
const [currentPage, setCurrentPage] = useState(1);

步骤2:修改按钮渲染逻辑,动态添加激活类

遍历页码按钮时,判断当前数字是否等于currentPage,匹配则添加active类:

<div className={style.Pagination_numbers}>
  <ul className={style.Pagination__ul}>
    {pageNumbers?.map((number) => (
      <li key={number} className={style.list}>
        <button 
          onClick={() => {
            pagination(number);
            setCurrentPage(number); // 更新当前页码状态
          }}
          className={number === currentPage ? style.active : ''}
        >
          {number}
        </button>
      </li>
    ))}
  </ul>
  <button className={style.backButton} onClick={prevPage}>Back</button>
  <button className={style.advanceButton} onClick={nextPage}>Next</button>
</div>

注意:如果你的pagination函数已经内部处理了页码更新逻辑,只需确保currentPage和分页逻辑中的页码保持同步即可,无需重复调用setCurrentPage。

步骤3:添加激活类的CSS样式

在你的CSS中新增active类的样式,覆盖默认按钮样式:

.list > button {
    height: 35px;
    width: 35px;
    margin: 5px;
    bottom: 19px;
    border-radius: 25px;
    font-weight: 200;
    left: 135px;
    color: rgb(255, 255, 255);
    cursor: pointer;
    background-color: #000000a2;
    position: relative;
}

.list > button:hover {
    color: rgb(255, 255, 255);
}

/* 新增激活态样式 */
.list > button.active {
    background-color: rgb(71, 117, 218);
    font-weight: 600; /* 可选:强化选中视觉效果 */
}

额外优化:禁用首尾页的切换按钮

可以根据当前页码给「Back」「Next」按钮添加禁用状态,提升交互体验:

<button 
  className={`${style.backButton} ${currentPage === 1 ? style.disabled : ''}`} 
  onClick={prevPage}
  disabled={currentPage === 1}
>
  Back
</button>
<button 
  className={`${style.advanceButton} ${currentPage === pageNumbers.length ? style.disabled : ''}`} 
  onClick={nextPage}
  disabled={currentPage === pageNumbers.length}
>
  Next
</button>

对应的CSS:

.backButton.disabled, .advanceButton.disabled {
    opacity: 0.5;
    cursor: not-allowed;
    background-color: #555;
}

内容的提问来源于stack exchange,提问作者Shoah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:30:44