How to add a CSS class to an element on click - React

前端 未结 4 1940
既然无缘
既然无缘 2021-01-03 01:46

How do you add a CSS class to an existing REACT element on click?

I have a JSFiddle created: https://jsfiddle.net/5r25psub/

In the fiddle, the code only wor

4条回答
  •  甜味超标
    2021-01-03 02:29

    Rather than using two state variables, you can do like this.

    Since the initial state of color is blue, you can change the handleClick function as :

    handleClick: function(){
     if (this.state.color === 'blue'){
      this.setState({color : "green"});
     } else {
       this.setState({color: 'blue'});
     }
    }
    

    And, for the className, consider a variable :

    let colorClass= this.state.color === "blue" ? "blue" : "green" 
    

    Now, replace the className as below and you need to enclose that object where you call div class.

    return ;
    

    I hope it works fine.

提交回复
热议问题