REACT - toggle class onclick

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

    Thanks to @cssko for providing the correct answer, but if you tried it yourself you will realise it does not work. A suggestion has been made by @Matei Radu, but was rejected by @cssko, so the code remains unrunnable (it will throw error 'Cannot read property bind of undefined'). Below is the working correct answer:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.addActiveClass = this.addActiveClass.bind(this);
        this.state = {
          active: false,
        };
      }
      addActiveClass() {
        const currentState = this.state.active;
        this.setState({
          active: !currentState
        });
      };
    
      render() {
        return ( <
          div className = {
            this.state.active ? 'your_className' : null
          }
          onClick = {
            this.addActiveClass
          } >
          <
          p > {
            this.props.text
          } < /p> < /
          div >
        )
      }
    }
    
    class Test extends React.Component {
      render() {
        return ( <
          div >
          <
          MyComponent text = {
            'Clicking this will toggle the opacity through css class'
          }
          /> < /
          div >
        );
      }
    }
    
    ReactDOM.render( <
      Test / > ,
      document.body
    );
    .your_className {
      opacity: 0.3
    }
    
    

提交回复
热议问题