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

前端 未结 2 1492
挽巷
挽巷 2021-01-11 13:57

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

  var App = React.createClass({
           


        
相关标签:
2条回答
  • 2021-01-11 14:30

    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.

    0 讨论(0)
  • 2021-01-11 14:40

    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.

    But to answer your question, you could do that way, but how often is your this.state.touchMode would 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):

    componentWillMount: function(){
        document.body.classList.add('touchMode');
    },
    componentWillUnmount: function(){
        document.body.classList.remove('touchMode');
    }
    
    0 讨论(0)
提交回复
热议问题