首页 > 解决方案 > Different classes with same classname imported seperately in different components, overrides one another - React

问题描述

Suppose I have a component ABC.tsx in which I have imported CSS file ABC.css.

ABC.css

.header{
width:10%;
}

Again, I have another component XYZ.tsx in which I have imported CSS file XYZ.css.

XYZ.css

.header{
width:100%;
}

These classes are used in their respective component.

However, when I run my app, I notice that class from XYZ is being applied to ABC or vice-versa. Shouldn't classes be applied locally only from those CSS files to the component in which they were imported?

Does react process all CSS and put them before all HTML tags and they are applied according to the order in which they were processed? I am saying this because I can see in in the inspect's element tag there are 2 tag before the HTML begins, both containing the same code.

标签: htmlcssreactjswebpack

解决方案


Actually styles in nested JS application will be applied to the header of your index file so it will affect any part of your code. If you are using CRA (If you not you may require react-scripts@2.0.0 or higher) one of the easiest ways to make this work is to use .module extension for your CSS files, to let the bundle creator make each class a unique one for you.

So let's say we got ABC.css we should add .module into it like this ABC.module.css and then import it like this:

import class from "ABC.module.css" // route to ABC.module.css
// rest of your file
return <div className={class.header}></div>

Besides the .module approach we can use many other great tools for scoping our CSS that available to React application like Styled Components, Emotion, and many others.

NOTE: Thanks to @hotpink, it is worth to mention, CSS styles on the same property will override each other based on their writing order or specificity, so this behavior that we saw here will not be limited to nested applications (e.g React) and it may happen everywhere in our frontend applications.


推荐阅读