简体   繁体   English

单击 React.js 中的按钮时删除活动的 class

[英]remove active class when click the button in React.js

I have 3 different element of toggle buttons and Nav.我有 3 个不同的切换按钮和导航元素。 How do I remove all actived class except that I just clicked?除了我刚刚单击之外,如何删除所有活动的 class?

Also I want to remove actived class when click body section.我还想在单击正文部分时删除活动的 class 。 What Do I need to change the code?我需要更改什么代码?

This is what I tried so far now.这是我到目前为止所尝试的。

export default function Page() { 
  const [show, setShow] = React.useState(); 
  const [show2, setShow2] = React.useState(); 
  const [show3, setShow3] = React.useState(); 
  return (
    <>
      <button className={`toggle1 ${show ? "toggle-active1" : ""}`} onClick={() => setShow(!show)}>
        Toggle1
      </button>
      <nav className={`btn-toggle1 ${show ? "btn-active1" : ""}`}>Navigation menu</nav>
      <button className={`toggle2 ${show2 ? "toggle-active2" : ""}`} onClick={() => setShow2(!show2)}>
        Toggle2
      </button>
      <nav className={`btn-toggle2 ${show2 ? "btn-active2" : ""}`}>Navigation menu2</nav>
      <button className={`toggle3 ${show3 ? "toggle-active3" : ""}`} onClick={() => setShow3(!show3)}>
        Toggle3
      </button>
      <nav className={`btn-toggle3 ${show3 ? "btn-active3" : ""}`}>Navigation menu3</nav>
    </>
  );
}

The quickest solution will be to use:最快的解决方案是使用:

const handleClick = (active) => {
  active !== 'ID_1' && setShow(!show)
  active !== 'ID_2' && setShow2(!show2)
  active !== 'ID_2' && setShow3(!show3)
}
    
onClick={() => handleClick('ID_1')}

Or you can storing name of the active element in state (I think it's a better aproach):或者您可以将活动元素的名称存储在 state 中(我认为这是一种更好的方法):

const [active, setActive] = useState('')

onClick={() => setActive('ID_1')}
className={`toggle1 ${active === 'ID_1' ? "toggle-active1" : ""}`}

Replace ID_1, ID_2, etc. with your custom identifier.将 ID_1、ID_2 等替换为您的自定义标识符。

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

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