简体   繁体   English

反应 css class 名称是全球性的?

[英]React css class names are global?

I'm not going to delve into the code too much in this question, instead, I'm looking for a high-level answer.我不会在这个问题中过多地深入研究代码,而是在寻找一个高级别的答案。

In my js, I have a div with the class name potato .在我的 js 中,我有一个带有 class 名称的 div potato I have a file called myStyles.css , and I imported that CSS file into my js file.我有一个名为myStyles.css的文件,我将该 CSS 文件导入到我的 js 文件中。 Now in my CSS, I targeted .potato , and do my styling.现在在我的 CSS 中,我以.potato为目标,并进行造型。 All good so far.到目前为止一切都很好。

Now I create a new js file, and in that new file I again have a div name by potato .现在我创建了一个新的 js 文件,在这个新文件中,我再次有一个 div 名称,名称为potato In this new js file, I do not import myStyles.css .在这个新的 js 文件中,我没有导入myStyles.css However, for some reason, the styling from myStyles.css is being applied to that div!但是,出于某种原因,来自myStyles.css的样式正在应用于该 div!

Please let me know why this is the case?请让我知道为什么会这样? Why is it pulling styling from an unimported file?为什么要从未导入的文件中提取样式?

If you need any actual code on my part to answer this question, please let me know and I can provide it.如果您需要我的任何实际代码来回答这个问题,请告诉我,我可以提供。

Thanks!谢谢!

I got the same problem which you are facing.我遇到了你面临的同样问题。 So if you make a simple css file with class then it will work as a global file.因此,如果您使用 class 制作一个简单的 css 文件,那么它将作为全局文件工作。 so the solutions are following:所以解决方案如下:

1-> Import css as module and use it 1-> 导入 css 作为模块并使用它

2-> Don't use same class or don't give css directly to element 2-> 不要使用相同的 class 或不要将 css 直接提供给元素

The css will be global for all components. css 将适用于所有组件。
Even if you import individual css for all components, it will still apply it to all other components.即使您为所有组件导入单独的 css,它仍会将其应用于所有其他组件。

To fix this, just add and "id" or "class" to the parent and then use that parent element's id to access its classes.要解决此问题,只需将“id”或“class”添加到父元素,然后使用该父元素的 id 来访问其类。

#myComponent .first{
   /* your css */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM