REACT - toggle class onclick

后端 未结 14 1974
长情又很酷
长情又很酷 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:15

    React has a concept of components state, so if you want to switch it, do a setState:

    constructor(props) {
      super(props);
    
      this.addActiveClass= this.addActiveClass.bind(this);
      this.state = {
        isActive: false
      }
    }
    
    addActiveClass() {
      this.setState({
        isActive: true
      })
    }
    

    In your component use this.state.isActive to render what you need.

    This gets more complicated when you want to set state in component#1 and use it in component#2. Just dig more into react unidirectional data flow and possibly redux that will help you handle it.

提交回复
热议问题