【问题标题】:Why is this ReactJS import structure not working?为什么这个 ReactJS 导入结构不起作用?
【发布时间】:2021-04-20 20:41:53
【问题描述】:

我目前正在使用 AirBnb React 风格指南 (https://airbnb.io/javascript/react/) 开发一个 React 项目

项目的结构是这样的(正如他们在第一章某处建议的那样):

src/
|- components/
|  |- Footer/
|  |  |- index.jsx
|  |- Navbar/
|  |  |- index.jsx
|  |- index.js
|- containers/
|  |- Layout/
|  |  |- index.jsx

我的导航栏如下所示:

// File: src/components/Navbar/index.jsx
import React from 'react';

export default function Navbar() {
  return <h1>Navbar</h1>;
}

我的页脚也一样,但不是Navbar,而是到处都是Footer

但是,我不想像这样导入组件:

// File: src/containers/Layout/index.jsx
import Footer from '../../components/Footer';
import Navbar from '../../components/Navbar';

但我想像这样导入它们:

import { Footer, Navbar } from '../../components';

所以我尝试在 components 文件夹中创建一个 index.js 文件,其内容如下:

import Footer from './Footer';
import Navbar from './Navbar';

export default { Footer, Navbar };

但是这给了我以下错误:

Failed to compile.

./src/containers/Layout/index.jsx
Attempted import error: 'Footer' is not exported from '../../components'.

为什么会这样?我尝试过使用以下替代方法: 备选方案 1

export { default as Footer } from './Footer';
export { default as Navbar } from './Navbar';

但这给了我同样的错误,我也试过import * as Footer from './Footer';然后再次导出,但没有成功..


编辑:

经过一些反馈,这是我的页脚文件:

// src/components/Footer/index.jsx
import React from 'react';

export default function Footer() {
  return <h1>Footer</h1>;
}

我现在像这样导出它:

// src/components/index.js
import Footer from './Footer';
import Navbar from './Navbar';

export { Footer, Navbar };

当我像这样导入它们时:

// src/containrs/Layout/index.js
import { Navbar, Footer } from '../../components';

export default function Layout({ children }) {
  return (
    <>
      <Navbar />
      {children}
      <Footer />
    </>
  );
}

解决方案:我的导出错误,我的 ReactJS 没有正确刷新(我猜是 CLI 错误?文件被缓存了..)

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您只能export 一个默认常量。

    在您的index.js 中更改为

    export { Footer, Navbar };
    

    【讨论】:

    • 我现在在我的 `components/index.js`` import Footer from './Footer'; import Navbar from './Navbar'; export { Footer, Navbar }; 中有这个错误:Failed to compile. src\containers\Layout\index.jsx Line 4:10: Footer not found in '../../components' import/named Search for the keywords to learn more about each error.
    • 你能显示你的页脚 (index.jsx) 文件吗?
    • 重启两次后突然就可以了,我认为是缓存,因为react cli没有正确刷新
    【解决方案2】:

    为了首先从单个文件中获取组件,您必须将它们导入 index.js 文件中,例如:

    组件/index.js

    import Footer from './Footer';
    import Navbar from './Navbar';
    
    export {
       Navbar 
       Footer 
    }
    

    然后你可以像这样导入组件:

    App.js

    import { Footer, Navbar } from '../../components';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 2019-11-19
      • 2020-09-01
      相关资源
      最近更新 更多