Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

reactjs - React CSS - how to apply CSS to specific pages only

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

My src folder structure looks something like this:

| pages
| - About
| - - index.js
| - - styles.css
| - Home
| - - index.js
| - - styles.css
| index.js
| index.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.

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

You have multiple solutions:

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- 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- Eject or use a fork of react-scripts (the engine of CRA) to use CSSModules (https://github.com/css-modules/css-modules)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...