我的 React 应用程序上有两条路线:/a 和 /b.
I have two routes on my React app: /a and /b.
对于/a,我希望body css 标签具有background-color: red;.
For /a, I want the body css tag to have a background-color: red;.
对于/b,我希望body css 标签具有background-color: blue;.
For /b, I want the body css tag to have a background-color: blue;.
a 和 b 两个组件都位于不同的 .JSX 文件中,并且都导入了自己的 main.scss 文件,该文件定义了各自的body background-color.
Both components a and b live in different .JSX files, and both import their own main.scss file which defines their own respective body background-color.
但是,由于整个应用程序都编译到了 body 标签中,因此似乎存在冲突,并且两个路由都只尊重 body 标签之一.
However, since the entire app is compiled into the body tag, there seems to be a conflict, and only one of the body tags is respected for both routes.
<body> <script src="bundle.js" type="text/javascript"></script> </body>我希望它在 body 标签上而不只是容器 div 上的原因是我希望 background-color 在我滚动到页面(Mac 和 iOS 上的反弹效果).
The reason I want it on the body tag and not just a container div is that I want the background-color to be visible when I scroll outside the bounds of the page (the bounce effect on Mac and iOS).
这样做的正确方法是什么?
What's the proper way to do this?
推荐答案发生这种情况是因为当您在没有 CSS Modules 的组件中导入样式时,这些样式是全局的,因此您的 body 样式被定义为两个次(您可以在 标签中看到所有样式).
That's happening because when you import your styles in your component without CSS Modules, the styles are global so your body style is defined two times (you can see all the styles in the <head> tag).
您可以通过在组件 componentDidMount() 方法中设置背景颜色来解决此问题.
You can fix that by setting the background color in your component componentDidMount() method.
示例
componentDidMount(){ document.body.style.backgroundColor = "red"// Set the style document.body.className="body-component-a" // Or set the class }更多推荐
React Routes
发布评论