React Routes - body css 标签上的不同样式 [英] React Routes - different styling on body css tag

查看:41
本文介绍了React Routes - body css 标签上的不同样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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;.

ab 两个组件都位于不同的 .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 - body css 标签上的不同样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆