简体   繁体   English

在 React 中有条件地设置活动 class

[英]Set active class conditionally in React

I am new to React and of course, I am facing problems, the thing I am trying to accomplish is this.我是 React 的新手,当然,我面临着问题,我想要完成的事情就是这个。 When any of these Components is opened I want to set an active class.当打开这些组件中的任何一个时,我想设置一个活动的 class。 I have already tried something but it is not working.我已经尝试过一些东西,但它不起作用。 So I want to add a background color to these divs className='menu__iconsRight ' when they are active.所以我想在这些 div 处于活动状态时为它们添加背景颜色className='menu__iconsRight ' I would appreciate the help.我将不胜感激。 Thanks谢谢

 const App = () => {

 const[isStyleOpen, setIsStyleOpen]=React.useState(false)
 const[isRectOpen, setIsRectOpen]=React.useState(true)
 const[isHairOpen, setIsHairOpen]=React.useState(false)

    function openHair(){
    setIsHairOpen(true)
    }
    function closeHair(){
      setIsHairOpen(false)
    }

     
    function openRect(){
     setIsRectOpen(true)
    }
    function closeRect(){
      setIsRectOpen(false)
     }
 
    

    function openStyle(){
     setIsStyleOpen(true)
    }
    function closeStyle(){
     setIsStyleOpen(false)
    }


     return (
      
          <div className='menu'>         
            <div className='menu__iconsRight ' >
            <img   onClick={() => setIsRectOpen(!isRectOpen)} 
              src="./images/icons/win.png"/>
              {isRectOpen ? <Rect />: null}
          </div>
       
           
            <div className={`?active: 'menu__iconsRight' `}    >
            <img    onClick={() => setIsStyleOpen((isStyleOpen) => 
             !isStyleOpen)} 
              src="https://winaero.com/blog/wp-content/uploads/2017/07/Co-win-- 
              icon.png"/>
               {isStyleOpen ? <Style  closeStyle={closeStyle}  />: null}
            </div>
       
              <div className='menu__iconsRight '>
                <img    onClick={() => setIsHairOpen(!isHairOpen)} 
              src="./images/icons/at.png"/>
               {isHairOpen ? <Hair closeHair={closeHair}  />: null}   
               </div>
              
            )
           }
         export default App

You can simply do something like:您可以简单地执行以下操作:

...
<div className={"menu__iconsRight " + ((isRectOpen) ? "active": "")}>
...

Is this what you're looking for?这是你要找的吗?

To handle more complex cases, you can use classnames :要处理更复杂的情况,您可以使用classnames

<div className={classnames("menu__iconsRight", {
  "active": isRectOpen
})}>

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

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