React CSS-如何仅将CSS应用于特定页面 [英] React CSS - how to apply CSS to specific pages only

查看:62
本文介绍了React CSS-如何仅将CSS应用于特定页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 create-react-app ,并且我正在尝试一种将样式表应用于特定页面的有效"方法.

I am using create-react-app and I am trying to work out an "efficient" way to apply stylesheets to specific pages.

我的 src 文件夹结构如下所示:

My src folder structure looks something like this:

| pages
| - About
| - - index.js
| - - styles.css
| - Home
| - - index.js
| - - styles.css
| index.js
| index.css

在每个 index.js 文件中,我使用 import'./style.css'

In each of the index.js files I use import './style.css'

但是,我发现当我从一个页面导航到下一个页面时,起始页面中的样式将被应用到目标页面,就好像它们已经被缓存并且目标页面中的样式没有被遵循一样.

However, I'm finding that when I navigate from one page to the next the styles from the starting page are being applied to the target page as if they're being cached and the styles from the target page are not being followed.

我只是想知道我是否误解了如何在React中将样式应用于特定页面.我应该制作完全包含样式的自包含组件吗?

I just wondered if I'm misunderstanding how to apply styles in React to specific pages. Should I be making entirely self contained components which incude the styles too?

我正在考虑以内联方式应用它们,但是我意识到使用JS样式时存在局限性.

I am considering applying them inline but I realise there are limitation when using JS styles.

推荐答案

创建react应用程序会将您的所有css文件捆绑为一个,因此所有样式都将在您应用程序中的每个位置(在每个渲染的组件上)可用.请注意,CRA是单页应用程序(SPA),因此您不能在DOM中的页面"中而是在呈现的组件"中进行思考.

Create react app will bundle all your css files into one so all the styles will be available everywhere in you app (on every rendered component). Be aware that CRA is a Single-Page Application (SPA) so you can't think in "pages" but rather in "rendered component" in the DOM.

您有多种解决方案:

1-在您的css文件中井井有条:使用组件名称为所有类加前缀,以避免发生冲突(例如BEM)或使用css hierachy .my-component>.my-class {...}

1- Be organized in you css files : prefix all your classes by your component name to avoid conflict (like BEM) or use css hierachy .my-component > .my-class {...}

<div className="my-component">
   <span className="my-class">Hello</span>
</div>

2-在JSX文件中声明所有样式:

2- declare all your style in your JSX files:

const styles= {
  myComponent: {
    fontSize: 200,
  },
};
const myComponent = () => (
  <span style={styles.myComponent}>Hello</span>
);

不利之处在于,默认情况下,您的样式不会由供应商作为前缀.

the downside is that your styles will not be vendor prefixed by default.

3-弹出或使用fork-react-scripts(CRA的引擎)来使用CSSModules( https://github.com/css-modules/css-modules )

3- Eject or use a fork of react-scripts (the engine of CRA) to use CSSModules (https://github.com/css-modules/css-modules)

这篇关于React CSS-如何仅将CSS应用于特定页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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