如何在ReactJS中的事件上添加或删除className? [英] How to add or remove a className on event in ReactJS?

查看:56
本文介绍了如何在ReactJS中的事件上添加或删除className?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对React还是很陌生,在将我的想法从标准js转换过来时我很挣扎.

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

在我的react组件中,我具有以下元素:

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?

推荐答案

类列表可以从组件的状态派生.例如:

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>;
  }
});

调用 this.setState 将触发组件的重新呈现.

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

这篇关于如何在ReactJS中的事件上添加或删除className?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆