尝试使用React.DOM设置主体样式

Gia*_*Elk 43 javascript reactjs react-jsx

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

我试过这段代码而且它不起作用:

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

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

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

yar*_*den 73

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

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

建议将它放在componentWillMount方法中,并在componentWillUnmount以下位置取消它:

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

componentWillUnmount: function(){
    document.body.style.backgroundColor = null;
}
Run Code Online (Sandbox Code Playgroud)

  • @DhavalJardosh 因为当改变身体样式的组件卸载时,你希望你的身体恢复到正常的“状态”。 (4认同)
  • 为什么要有`componentWillUnmount`? (3认同)

小智 21

使用功能组件和 useEffect 钩子:

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

    return () => {
        document.body.classList.remove('bg-black');
    };
});
Run Code Online (Sandbox Code Playgroud)