html - 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.
解决方案
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.
推荐阅读
- reactjs - 可以在 promise 的 THEN 构造中调度操作吗?
- asp.net - Blazor IdentityServer 身份验证
- android - 从网站获取 HTML 代码到 EditText 上的 setText
- c - 带有初始化问题的 C 结构定义
- reactjs - AgGrid 反应材料 UI
- xml - C# 例程中的 XML/XSL 转换问题以输出带有嵌入 CSS 内容的 HTML
- react-native - 有人可以在本机反应中提出以下错误的解决方案吗
- hadoop - hadoop + 如何重新平衡 hdfs
- python - 在我的情况下,如何解决“元组”对象没有属性“节奏”
- node.js - MongoDB 使用对象数组作为搜索参数查找文档