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)
小智 21
使用功能组件和 useEffect 钩子:
useEffect(() => {
document.body.classList.add('bg-black');
return () => {
document.body.classList.remove('bg-black');
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42293 次 |
| 最近记录: |