Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

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

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:

<div className='base-state' onClick={this.handleClick}>click here</div>

The behaviour I am looking for is to add an extra class on click. My first idea was to try and add the class in the click handler function e.g.

handleClick : function(e) {
   <add class "click-state" here>
}

I haven't been able to find any examples that do anything similar though, so I am fairly sure I am not thinking about this in the right way.

Can anyone point me in the right direction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...