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

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

问题描述

我对React很陌生,我正在努力将我的想法从标准j转换。

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?

推荐答案

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

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天全站免登陆