Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

javascript - 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. When any of these Components is opened I want to set an active 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. 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply do something like:

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

Is this what you're looking for?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...