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

Trying to use React.DOM to set body styles

本文关键字:设置 正文 样式 DOM React      更新时间:2023-09-26

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

假设你的身体标签不是另一个 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;
}

带有功能组件和 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'
    }
} 

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

反应和流星测试:

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 ;
}
这就是

我最终使用的。

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

即使您可以使用提供的答案从 react 设置正文样式,我更喜欢组件只负责设置自己的样式。

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

首先,我将这种样式添加到索引.html标题中。

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

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