gpt4 book ai didi

javascript - 在 create-react-app 应用程序中导入 css 文件和 react 组件?

转载 作者:行者123 更新时间:2023-11-29 10:05:10 32 4
gpt4 key购买 nike

我刚开始使用 react.js 和 create-react-app 应用程序,如果这是一个明显的问题,请原谅。

我的“src”文件夹结构是这样的:

scr/
....components/
........ComponentA.jsx
........Componentb.jsx
....styles/
........ComponentA.css
....App.css
....App.js
....App.test.js
....index.css
....index.js
...OTHER DEFAULT FILES

在 App.js 中我有这个:

import React, { Component } from 'react';
import ComponentA from './components/ComponentA';

class App extends Component {
render() {
return (
<div className="App">
<ComponentA />
</div>
);
}
}

export default App;

ComponentA 我有这个:

import React, { Component } from 'react';
import './styles/ComponentA.css';
import ComponentB from './components/ComponentB';

class ComponentA extends Component {
render() {
return (
<div className="componentAStyle">
<ComponentB />
</div>
);
}
}

export default ComponentA;

ComponentB 我有这个:

import React, { Component } from 'react';

class ComponentB extends Component {
render() {
return (
<div>
<h1>Hello from ComponentB</h1>
</div>
);
}
}

export default ComponentB;

我想做的只是从 ComponentA 中导入 ComponentB 并为 ComponentA 导入样式,但是今年秋天显示的是以下消息:

Failed to compile
./src/components/ComponentA.jsx
Module not found: Can't resolve './styles/ComponentA.css' in 'C:\xampp\htdocs\custom-k39\src\components'
This error occurred during the build time and cannot be dismissed.

如果我删除 css 导入,则会出现另一条错误消息:

Failed to compile
./src/components/ComponentA.jsx
Module not found: Can't resolve './components/ComponentB' in 'C:\xampp\htdocs\custom-k39\src\components'
This error occurred during the build time and cannot be dismissed.

如何从另一个组件及其各自的 css 导入另一个组件?

谢谢。

最佳答案

您需要使导入的路径相对于执行导入的文件的当前位置。

正确的导入应该是

组件 A

import React, { Component } from 'react';
import '../styles/ComponentA.css';
import ComponentB from './ComponentB';

你可以在 https://glitch.com/edit/#!/trashy-unicorn 看到这个工作.
(点击左上角的 Show Live。)

当前发生的错误是

import ComponentB from './components/ComponentB';

正在寻找路径

src/components/components/ComponentB

它不存在,所以给你一个错误。您的样式也发生了同样的事情。

希望这对您有所帮助。

关于javascript - 在 create-react-app 应用程序中导入 css 文件和 react 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44999651/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com