简体   繁体   English

如何将 Toggle Class 添加到 React.js 的链接?

[英]How to add Toggle Class to links with React.js?

I need to add toggle class active after clicking on the links has menu.单击链接有菜单后,我需要添加 toggle class active。

const AllLinksNavbar = Array.from(
        document.querySelectorAll(".has-menu")
    )

    AllLinksNavbar.forEach( element => {
        element.addEventListener('click', (e) => {
            e.preventDefault();
            element.classList.toggle('active')
        });
    } )

in react we work with states.在 React 中,我们与各州合作。 you need to create state with const [className, setClassName] = useState("someClass");您需要使用const [className, setClassName] = useState("someClass");创建 state then you need to change this class by the function setClassName那么您需要通过 function setClassName更改此 class

onClick={()=>{ 
  if(className.includes("active")){
     setClassName(className.replace("active",""))
  } else {
     setClassName(className + " active")
  }
}}

then use this state as a class name for the element然后使用这个 state 作为元素的 class 名称

<div className={className}> </div>

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

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