javascript 使用 React.js 时,何时、何地以及如何将类添加到 document.body

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26694570/
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-10-28 06:19:47  来源:igfitidea点击:

When, where and how to add class to the document.body when using React.js

javascriptreactjs

提问by SM79

Currently I am doing this, but this is not the react.js way, right? Is render() the right place? What is the alternative?

目前我正在这样做,但这不是 react.js 的方式,对吗?render() 是正确的地方吗?什么是替代方案?

  var App = React.createClass({
    render: function() {
      if (this.state.touchMode === 2) {
          $('body').addClass('touchMode');
      }

      return (<div> etc /div>)
    }
  )}

采纳答案by Brigand

It's best to keep this logic outside of your component. Event emitters are a good way to abstract this.

最好将此逻辑保留在组件之外。事件发射器是一个很好的抽象方法。

var globalEvents = new EventEmitter();

var App = React.createClass({
  setTouchMode: function(touchMode){
     globalEvents.emit('touchModeChange', touchMode);
  },
  render: ...
});

// outside any react class
globalEvents.on('touchModeChange', function(mode){
  if (mode === 2) {
    $('body').addClass('touchMode');
  }
  else {
    $('body').removeClass('touchMode');
  }
});

If it really needs to be part of the state of one or more components, they can also listen to the event and update their state in the handler.

如果它真的需要成为一个或多个组件状态的一部分,它们也可以监听事件并在处理程序中更新它们的状态。

回答by trekforever

Well ideally adding a class to the body would break the encapsulation that React components provide and fiddling with the DOM outside React could cause trouble if the body gets re-rendered. If possible, rather than adding the class to the document body, I would just add it to a component root element that React manages.

理想情况下,向主体添加一个类会破坏 React 组件提供的封装,并且如果主体被重新渲染,在 React 外部摆弄 DOM 可能会导致麻烦。如果可能,我不会将类添加到文档正文中,而是将其添加到 React 管理的组件根元素中。

But to answer your question, you could do that way, but how often is your this.state.touchModewould change? If it's something that only changes during mount/unmount of the component, you can do it in componentWillMount(so that it only runs once when component mount, rather than every single time during render):

但是要回答您的问题,您可以这样做,但是您多久this.state.touchMode更改一次?如果它只在组件的挂载/卸载期间发生变化,您可以在其中进行componentWillMount(这样它在组件挂载时只运行一次,而不是在渲染期间每次都运行):

componentWillMount: function(){
    document.body.classList.add('touchMode');
},
componentWillUnmount: function(){
    document.body.classList.remove('touchMode');
}