javascript-尝试使用React.DOM设置主体样式
如何使用React.DOM更改HTML document.body.style.backgroundColor = "green";
上的样式?
我尝试了这段代码,但无法正常工作:
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更改每条路线的页面背景颜色?
Giant Elk asked 2020-08-10T06:09:27Z
3个解决方案
72 votes
假设您的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;
}
3 votes
将多个属性从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'
}
}
2 votes
加载或附加额外类的最佳方法是在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 ;
}