If you want to localize CSS rules, then you would have to switch to modular stylesheets (works the same for sass stylesheets).
In your current structure, the component imports non-modular stylesheet and doesn't localize the changes with a unique identifier. Therfore added rules live in a global scope without a unique identifier that would localize them so that only selected components could understand them. That means that they are capable of easily overwriting the same-named rules which were previously established (import order matters here, because it would dictate how the bundler appends the output stylesheet).
So instead of holding component-related rules within ./style.scss
file, rename it to ./index.module.scss
and then you would utilize it within the component like so:
import React from 'react';
import styles from './index.module.scss';
const HomePage = () => {
return (
<div className={style.homepage}>
<h1 className={style.heading}>Landing page</h1>
</div>
);
};
export default HomePage;
and your stylesheet would look like:
.heading {
color: #f3f3f3;
font-family: "Cambria";
font-weight: normal;
font-size: 2rem;
}
disclaimer:
I've changed the styling convention from selecting elements by their tag, to selecting them by class, because targetting elements by tag is widely considered a bad practice [ref] , but if you want to maintain it, then you would have to provide a parent scope for such a rule (it already exists since the parent <div/>
element has an assigned class.
In this case the implementation would look like:
import React from 'react';
import styles from './index.module.scss';
const HomePage = () => {
return (
<div className={style.homepage}>
<h1>Landing page</h1>
</div>
);
};
export default HomePage;
and styles:
.homepage {
h1 {
color: #f3f3f3;
font-family: "Cambria";
font-weight: normal;
font-size: 2rem;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…