REACT - toggle class onclick

后端 未结 14 1722
长情又很酷
长情又很酷 2020-11-27 11:40

I am trying to figure out how to toggle an active class onClick to change CSS properties.

I have taken many approaches, and read many SO answers. Using

相关标签:
14条回答
  • 2020-11-27 12:19

    I would prefer using "&&" -operator on inline if-statement. In my opinnion it gives cleaner codebase this way.

    Generally you could be doing something like this

    render(){
    return(
      <div>
        <button className={this.state.active && 'active'}
          onClick={ () => this.setState({active: !this.state.active}) }>Click me</button>
      </div>
    )
    }
    

    Just keep in mind arrow function is ES6 feature and remember to set 'this.state.active' value in class constructor(){}

    this.state = { active: false }
    

    or if you want to inject css in JSX you are able to do it this way

    <button style={this.state.active && style.button} >button</button>
    

    and you can declare style json variable

    const style = { button: { background:'red' } }
    

    remember using camelCase on JSX stylesheets.

    0 讨论(0)
  • 2020-11-27 12:19

    you can add toggle class or toggle state on click

    class Test extends Component(){
      state={
      active:false, 
     }
      toggleClass() {
        console.log(this.state.active)
        this.setState=({
         active:true,
       })
      }
    
        render() {
        <div>
          <div onClick={this.toggleClass.bind(this)}>
            <p>1</p>
          </div>
        </div>
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题