【问题标题】:React import component from another folder issue从另一个文件夹问题中反应导入组件
【发布时间】:2019-11-06 03:21:54
【问题描述】:

我确实添加了文件夹结构,所以你可以看到。

如何将图像组件导入卡片组件?不管我尝试什么路径,我都会收到此错误

./src/Components/Card/Card.js
Module not found: Can't resolve '../../Components/Image' in 
'/Users/user/project/projecttest/src/Components/Card'


import React from 'react'
import styled, {ThemeProvider, css } from 'styled-components'
import Image from '../../Components/Image'

【问题讨论】:

标签: javascript reactjs react-native


【解决方案1】:

不,我看到你在导入:import Image from '../../Components/Image'。这意味着您导入了indexImage folder

但是在您的代码中,您定义了Image.js 而不是index.js。 所以,你必须像这样导入:

import Image from '../Image/Image' 

或者,您可以将文件Image.js 重命名为index.js 以缩短导入时的代码:

// rename Image.js to index.js
// then, import file:
import Image from '../Image' 

【讨论】:

    【解决方案2】:

    你应该把 Image 写在最后或者把文件名改成 index.js

    import Image from '../../Components/Image/Image'
    
    

    【讨论】:

    • 完全正确:import Image from '../Image/Image'
    【解决方案3】:

    在 react 中尝试绝对导入。在根目录中创建一个 .env 文件。文件内容

    NODE_PATH=src

    【讨论】:

    【解决方案4】:

    @Jikun L 答案是正确的。我想知道为什么它不是图像格式。

    也许将文件夹结构更改为:

    组件

    -- 卡片

    ---> index.js

    ---> 样式.js

    -- 图像

    ---> xxx.png

    ---> package.json

    包.json:

    {
        "name": "@image"
    }
    

    在卡片中(index.js)

      <Image
        source={require("@images/xxx.png")}
      />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 2022-06-13
      • 2018-10-30
      • 1970-01-01
      • 2018-07-11
      • 2019-05-22
      • 2017-05-25
      相关资源
      最近更新 更多