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

Import css files and react components in a create-react-app application?

我刚开始使用 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

不存在,因此给您一个错误。您的样式也发生了同样的事情。

希望对您有所帮助。