简体   繁体   English

如何将 CSS 文件导入 React JS 应用程序?

[英]How to import CSS files to React JS application?

I am creating an application, created multiple CSS files but those are not able to import.我正在创建一个应用程序,创建了多个 CSS 文件,但这些文件无法导入。

I tried by installing css-loader and style-loader.我尝试安装 css-loader 和 style-loader。 But it doesn't help但它没有帮助

Please look below picture, I have Burger.css file.请看下图,我有Burger.css文件。 but it not visible to import但导入不可见

在此处输入图片说明

VS Code by default doesn't autocomplete all file types.默认情况下,VS Code 不会自动完成所有文件类型。 If you write import ./Burger/Burger.css or import ./Burger/BurgerIngredient/BurgerIngredient.css in your Layout.js file, your css files will be loaded fine.如果您在 Layout.js 文件中编写import ./Burger/Burger.cssimport ./Burger/BurgerIngredient/BurgerIngredient.css ,您的 css 文件将被正常加载。

If you want to use autocomplete for all files in VS Code, you can use this extension.如果要对 VS Code 中的所有文件使用自动完成功能,可以使用此扩展名。

https://marketplace.visualstudio.com/items?itemName=ionutvmi.path-autocomplete https://marketplace.visualstudio.com/items?itemName=ionutvmi.path-autocomplete

Without Extension无扩展

无扩展

With Extension带扩展

在此处输入图片说明

Ok since you confirmed that your ./Layout.css import does not work, you should not name your import when it's about a css file.好的,因为您确认您的./Layout.css导入不起作用,所以当它与 css 文件有关时,您不应该命名您的导入。 Doing :正在做 :

import './myFile.css';

is enough to apply your css.足以应用你的css。

Note that css is global in React, so you might want to use styled component or encapsulate your css to prevent side effect on other components).请注意,css 在 React 中是全局的,因此您可能希望使用styled component或封装您的 css 以防止对其他组件产生副作用)。

Now, if you really want to add style the way you tried to, there is the style attribute which accepts an object.现在,如果您真的想按照您尝试的方式添加样式,则可以使用style属性来接受一个对象。 So you could do:所以你可以这样做:

<div style={{backgroundColor: 'red'}}>Hello World !</div>

Note that the css properties are written in camelCase .请注意,css 属性是用camelCase编写的。

Your file structure appears to me to be...你的文件结构在我看来是...

-Burger
--BurgerIngredient
----Burger.css
--Layout
----Layout.css

Your primary application, from what it appears here, is in /Burger .从此处显示的内容来看,您的主要应用程序位于/Burger Considering that, when you type import, you see the dropdown appear, showing helpful suggestions, and it lists...考虑到这一点,当您输入 import 时,您会看到下拉列表出现,显示有用的建议,并列出...

-../Burger/BurgerIngredient/...

As a possible, valid location.作为可能的有效位置。 In that case, why don't we try importing css, by typing out...在这种情况下,我们为什么不尝试导入 css,通过输入...

import burgercss from '../Burger/BurgerIngredient/Burger.css';

Note, for instance, Burger.css wouldn't show up until you select BurgerIngredient , because that's its conntaining folder.请注意,例如,在您选择BurgerIngredient之前, Burger.css不会显示,因为那是它的包含文件夹。

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

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