简体   繁体   English

在 ReactJS 中单击按钮时,如何添加活动的 class

[英]How can I add an active class when a button is clicked in ReactJS

What i want to acheive is to have an active class when a link is clicked.我想要实现的是在单击链接时有一个活动的 class 。 I'm using react我正在使用反应

This is the pagination.js file where I want to have the active class on each number clicked这是 pagination.js 文件,我希望在每个点击的数字上都有活动的 class

 const Pagination = ({ recordsPerPage, totalRecords, paginate }) => {
    
    const pageNumbers = []

    for(let i = 1; i <= Math.ceil(totalRecords / recordsPerPage); i++) {
        pageNumbers.push(i)
    }
    return (
        
        <ul className='pagination center'>
           <li class="disabled"><a href="#!"><i class="material-icons">chevron_left</i></a></li>

               {pageNumbers.map(number => (
                   <li key={number} style={{ marginLeft: '5px'}}>
                       <a href='#!' className='hoverable' onClick={() => paginate(number)}>
                         {number}
                       </a>
                   </li>
               ))}

           <li class="waves-effect"><a href="#!"><i class="material-icons">chevron_right</i></a></li>
            
        </ul> 
    )
}

You can just add a state here, when your onclick fire, set the state of current index您可以在此处添加 state,当您的 onclick 着火时,设置当前索引的 state

const Pagination = ({ recordsPerPage, totalRecords, paginate }) => {
    const [activePage, setActivePage] = useState(0);

    const pageNumbers = []

    for(let i = 1; i <= Math.ceil(totalRecords / recordsPerPage); i++) {
        pageNumbers.push(i)
    }

    const handlePaginate = (index) => {
        setActivePage(index);
        paginate(index)
    }

    return (
        
        <ul className='pagination center'>
           <li class="disabled"><a href="#!"><i class="material-icons">chevron_left</i></a></li>

               {pageNumbers.map(number => (
                   <li key={number} style={{ marginLeft: '5px'}} className={activePage === number && 'active'}>
                       <a href='#!' className='hoverable' onClick={() => handlePaginate(number)}>
                         {number}
                       </a>
                   </li>
               ))}

           <li class="waves-effect"><a href="#!"><i class="material-icons">chevron_right</i></a></li>
            
        </ul> 
    )
}

As for initial state, right now just default to 0, but it should be whatever current page you are on.至于最初的 state,现在只是默认为 0,但它应该是你当前所在的页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM