简体   繁体   English

从react js中的子文件夹导入模块

[英]import module from a sub folder in react js

Hello i am just learning ReactJs, I am trying to import a module from a sub folder in react, here is my folder structure 您好,我只是在学习ReactJs,我正在尝试从React的子文件夹中导入模块,这是我的文件夹结构

-src
---components
-----layout
-------Header.js
-------Navigation.js
-----fakeAuth.js

From the Header.js module, i am trying to import the fakeAuth from the parent (component), but it seems it can't call module or am i just missing something? 从Header.js模块,我试图从父级(组件)导入fakeAuth,但似乎无法调用模块,或者我只是缺少什么?

I already tried the following 我已经尝试了以下

import fakeAuth from './fakeAuth'
import fakeAuth from '././fakeAuth'
import fakeAuth from '../../fakeAuth'

Still no luck, i know this will be easy for some. 还是没有运气,我知道这对某些人来说很容易。 Thanks 谢谢

here i my fakeAuth.js, which is from the react-router-dom tutorial. 在这里,我是我的fakeAuth.js,它来自react-router-dom教程。

module.exports  = {
    isAuthenticated: false,
    authenticate(cb) {
      this.isAuthenticated = true;
      setTimeout(cb, 100); // fake async
    },
    signout(cb) {
      this.isAuthenticated = false;
      setTimeout(cb, 100);
    }
  };

It should be import fakeAuth from '../fakeAuth' 它应该是import fakeAuth from '../fakeAuth'

You just have to go 1 folder up where you have fakeAuth.js file. 您只需要向上打开1个文件夹,即可在其中找到fakeAuth.js文件。 adding '..' does that. 添加“ ..”即可。

Since you're using module.exports you can import in the following fashion inside Header.js : 由于使用的是module.exports ,因此可以在Header.js中以以下方式导入:

import { isAuthenticated, authenticate, signout  } from "../fakeAuth";

CodeSandbox Demo CodeSandbox演示

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

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