How to add or remove a className on event in ReactJS?

前端 未结 2 1046
难免孤独
难免孤独 2020-12-13 19:13

I am quite new to React and I am struggling a little with converting my thinking from standard js.

In my react component I have the following element:



        
相关标签:
2条回答
  • 2020-12-13 19:40

    You could use just a Vanilla JS (event.target and classList):

    handleClick = event => event.target.classList.add('click-state');
    
    render() {
      return <div className="base-state" onClick={this.handleClick}>Click here</div>;
    }
    

    BUT don't do that!

    React should handle changes in the DOM, so rely on modifying CSS classes via React.

    Event.target

    Element.classList

    React / Styling and CSS

    0 讨论(0)
  • 2020-12-13 19:54

    The list of classes can be derive from the state of the component. For example:

    var Component = React.createClass({
      getInitialState: function() {
        return {
          clicked: false
        };
      },
    
      handleClick: function() {
        this.setState({clicked: true});
      },
    
      render: function() {
        var className = this.state.clicked ? 'click-state' : 'base-state';
        return <div className={className} onClick={this.handleClick}>click here</div>;
      }
    });
    

    Calling this.setState will trigger a rerender of the component.

    0 讨论(0)
提交回复
热议问题