Trying to use React.DOM to set body styles

為{幸葍}努か 提交于 2019-12-17 22:23:01

问题


How can I use React.DOM to change styles on HTML body?

I tried this code and it's not working:

var MyView = React.createClass({
  render: function() {
    return (
      <div>
        React.DOM.body.style.backgroundColor = "green";
        Stuff goes here.
      </div>
    );
  }
});

If you execute this from the browsers console it works (but I need it working in ReactJS code): document.body.style.backgroundColor = "green";

Also see this question for similar but different solution: Change page background color with each route using ReactJS and React Router?


回答1:


Assuming your body tag isn't part of another React component, just change it as usual:

document.body.style.backgroundColor = "green";
//elsewhere..
return (
  <div>
    Stuff goes here.
  </div>
);

It's recommended to put it at componentWillMount method, and cancel it at componentWillUnmount:

componentWillMount: function(){
    document.body.style.backgroundColor = "green";
}

componentWillUnmount: function(){
    document.body.style.backgroundColor = null;
}



回答2:


A good solution to load multiple atributes from a js class to the document body can be:

componentWillMount: function(){
    for(i in styles.body){
        document.body.style[i] = styles.body[i];
    }
},
componentWillUnmount: function(){
    for(i in styles.body){
        document.body.style[i] = null;
    }
},

And after you write your body style as long as you want:

var styles = {
    body: {
        fontFamily: 'roboto',
        fontSize: 13,
        lineHeight: 1.4,
        color: '#5e5e5e',
        backgroundColor: '#edecec',
        overflow: 'auto'
    }
} 



回答3:


The best way to load or append extra classes is by adding the code in componentDidMount().

Tested with react and meteor :

componentDidMount() {
    var orig = document.body.className;
    console.log(orig);  //Just in-case to check if your code is working or not
    document.body.className = orig + (orig ? ' ' : '') + 'gray-bg'; //Here gray-by is the bg color which I have set
}
componentWillUnmount() {
    document.body.className = orig ;
}


来源:https://stackoverflow.com/questions/25474803/trying-to-use-react-dom-to-set-body-styles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!