React import folder navigation

淺唱寂寞╮ 提交于 2021-01-28 11:52:24

问题


I am trying to import images from an assets folder in my src folder in my react app but for some reason the path is not being recognised.

My folder structure is as follows:

|src
 |Assets
 |Common
 |Components

I am trying to import the image located in the assets folder from the components folder. I was able to import from my common folder to files in the components folder by doing the following:

import * as Constants from '../Common/Constants';

However following this same structure for loading images has not worked

<img src = '../Assets/myimg.png'></img>

What am I doing wrong?

Thanks


回答1:


In your code you're providing the image source based on your React app's location, which is neither related to web application's root location, nor media or static files locations (to be configured), so the browser will not know how to render it. Depending on what server you use (nginx, Express) you have to configure your static and/or media files and then specify in your image source based on how you configured.

In your present situation you can do the following:

Import

const reactImage = require("../Assets/myimg.png");

And then use it:

<img src={reactImage.default} />

If you had media files already configured on your server and properly resolving, it would be just

<img src="/media/Assets/myimg.png" />

Assuming media location is already configured and is pointing to the parent directory of your Assets.

In your example you were assuming the relative path of your React import and the image source hardcoded into image tag are same, but they are actually not.



来源:https://stackoverflow.com/questions/61262288/react-import-folder-navigation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!