尝试使用React.DOM设置主体样式 [英] Trying to use React.DOM to set body styles

查看:476
本文介绍了尝试使用React.DOM设置主体样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用React.DOM更改HTML上的样式 body

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>
    );
  }
});

如果从浏览器控制台执行此操作,它可以工作(但我需要它在ReactJS代码中工作):
document.body.style.backgroundColor =green;

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

另请参阅此问题类似但不同的解决方案:
使用ReactJS和React Router更改每条路线的页面背景颜色?

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

推荐答案

假设您的身体标签不是其中的一部分另一个React组件,只需像往常一样进行更改:

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>
);

建议将它放在 componentWillMount 方法,并在 componentWillUnmount 取消它:

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;
}

这篇关于尝试使用React.DOM设置主体样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆