Javascript 如何在 ReactJS 中添加或删除事件上的 className

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28732253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:19:30  来源:igfitidea点击:

How to add or remove a className on event in ReactJS

javascriptnode.jsreactjs

提问by Finglish

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

我对 React 还是很陌生,我在将我的想法从标准 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?

任何人都可以指出我正确的方向吗?

回答by Felix Kling

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.setStatewill trigger a rerender of the component.

调用this.setState将触发组件的重新渲染。

回答by Adrian Bienias

You could use just a vanilla JS: event.target and classList BUT don't' do that

你可以只使用一个普通的 JS: event.target 和 classList但不要这样做

handleClick = event => event.target.classList.add('click-state');

render() {
  return <div className="base-state" onClick={this.handleClick}>click here</div>;
}

https://developer.mozilla.org/en-US/docs/Web/API/Event/target

https://developer.mozilla.org/en-US/docs/Web/API/Event/target

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

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

React 应该处理 DOM 中的更改,因此依赖于通过 React 修改 CSS 类。

https://reactjs.org/docs/faq-styling.html

https://reactjs.org/docs/faq-styling.html