Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - useState, setting icon active and inactive

Hi all I have following code : my code

I have two useStates, they checking if first one is true then they set active icon if false then inactive icon.

    const [icon, setIcon] = useState(false);
    const [v, setV] = useState(Viber);
     function handleClick() {
       setIcon(true);
       icon ? setV(Viber) : setV(ViberChecked);
       setIcon(false);
     }

    return (
        <div className="App">
          <img src={v} alt="icon" onClick={handleClick} />
        </div>
     );

I think it working in right way, but it works only one time, how can I change my state after all clicks, I mean to set inactive then after click from inactive to active and so on.It should be like something as checkbox

Please help me to resolve this issue, thanks.


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

1 Answer

0 votes
by (71.8m points)

You literally set icon to true, then check if icon is true, then set icon false. Why is that? Your icon will always be true in this case

You can do something like this instead: (Check the working sandbox )

function handleClick() {
       if(icon){
         setV(Viber)
         setIcon(false)
       }else{
         setV(ViberChecked);
         setIcon(true);
       }
     }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...