尝试使用 React.DOM 来设置正文样式
Trying to use React.DOM to set body styles
如何使用 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%。
相关文章:
- 未捕获的类型错误:无法设置属性'innerHTML'如果为null,则将脚本移动到正文不会;不起作用
- 设置正文高度宽度 CSS 表达式
- “发送后无法设置标头”和空发布请求正文
- 无法使用模板帮助程序设置正文类
- 如何设置iframe以自动填充HTML中的空白正文空间
- 如何设置正文相对于屏幕大小的字体大小
- 设置正文显示样式 无 与一个子显示样式块
- 如何在 jquery 中设置另一个视图的正文内容
- 将 jquery 代码设置为正文页面加载
- 设置网站正文最小宽度
- 如何将此 Jquery 代码设置为正文加载
- 背景大小设置为包含的正文标签上的位置和缩放元素
- 将正文的背景图片设置为用户输入的带有Javascript的URL
- 在颜色框 iframe 上设置正文字体大小
- 尝试使用 React.DOM 来设置正文样式
- 在laravel的HTML正文中设置一个javascript值
- 正文没有设置正确的内容高度
- 正文上的香草JavaScript设置样式
- 使用Javascript设置正文左边距
- 在应用程序的根目录中设置正文解析器后,我是否需要连接多方进行快速处理