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

问题描述 投票:0回答:6

如何使用 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 更改每个路由的页面背景颜色?

javascript reactjs
6个回答
131
投票

假设你的 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;
}

23
投票

具有功能组件和 useEffect 钩子:

useEffect(()  => {
    document.body.style.backgroundColor = 'green';

    return () => {
        document.body.style.backgroundColor = 'transparent';
    };
});

4
投票

将多个属性从 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'
    }
} 

4
投票

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

使用react和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 ;
}

2
投票

这就是我最终使用的。

import { useEffect } from "react";

export function useBodyStyle(style: any){
    useEffect(()=>{
        for(var key in style){
            window.document.body.style[key as any] = style[key];
        }
        return () => {
            window.document.body.style[key as any] = '';
        }
    }, [style])
}

1
投票

即使您可以通过与提供的答案进行反应来设置主体样式,我更喜欢组件只负责设置自己的样式。

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.