尝试使用 React.DOM 设置 body 样式

IT技术 javascript reactjs react-jsx
2021-04-20 12:01:55

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

我试过这段代码,但它不起作用:

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

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

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

6个回答

假设你的 body 标签不是另一个 React 组件的一部分,只需像往常一样更改它:

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

建议把它放在componentWillMount方法,取消它componentWillUnmount

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

componentWillUnmount: function(){
    document.body.style.backgroundColor = null;
}
我看到的是,每当我们离开页面或离开该组件时,它都会自动清除状态。如果我错了,请纠正我,并感谢您的回复。
2021-05-23 12:01:55
@DhavalJardosh 因为当改变身体样式的组件卸载时,你希望你的身体恢复到正常的“状态”。
2021-05-25 12:01:55
除了这不是状态。这是DOM操作。当您离开组件时,这将保持不变,除非您将其重新设置为 ComponentWillUnmount
2021-05-29 12:01:55
为什么要有componentWillUnmount
2021-06-11 12:01:55
在直接导航到页面时,React 崩溃了,因为文档尚未定义。
2021-06-15 12:01:55

带有功能组件和 useEffect 钩子:

useEffect(()  => {
    document.body.classList.add('bg-black');

    return () => {
        document.body.classList.remove('bg-black');
    };
});

将多个属性从 js 类加载到文档正文的一个很好的解决方案可以是:

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

在你写下你想要的体型之后:

var styles = {
    body: {
        fontFamily: 'roboto',
        fontSize: 13,
        lineHeight: 1.4,
        color: '#5e5e5e',
        backgroundColor: '#edecec',
        overflow: 'auto'
    }
} 
@DhavalJardosh 以便在组件从 DOM 卸载时发生副作用并清理组件
2021-05-28 12:01:55
为什么componentWillUnmount
2021-06-07 12:01:55

加载或附加额外类的最佳方法是在 componentDidMount() 中添加代码。

react和流星测试

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

即使您可以通过对提供的答案做出react来设置正文样式,我还是更喜欢组件只负责设置自己的样式。

就我而言,有一个替代解决方案。我需要改变身体的背景颜色。这可以轻松实现,而无需更改 React 组件中的主体样式。

首先,我将此样式添加到 index.html 标题中。

<style>
    html, body, #react-app {
        margin: 0;
        height: 100%;
    }
</style>

然后,在最外面的组件中,我将 backgroundColor 设置为所需的值,将高度设置为 100%。