反应导入文件夹导航 [英] React import folder navigation

查看:65
本文介绍了反应导入文件夹导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的React应用程序的src文件夹中的Assets文件夹中导入图像,但是由于某种原因,路径未被识别.

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.

我的文件夹结构如下:

|src
 |Assets
 |Common
 |Components

我正在尝试从components文件夹导入位于assets文件夹中的图像.通过执行以下操作,我可以将我的公用文件夹中的内容导入到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>

我在做什么错了?

谢谢

推荐答案

在您的代码中,您将根据React应用程序的位置提供图像源,该位置与Web应用程序的根目录位置都不相关,也与 media 静态文件位置(要配置),因此浏览器将不知道如何呈现它.根据您使用的服务器( nginx Express ),您必须配置静态和/或 media 文件然后根据您的配置在图像源中指定.

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:

导入

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

然后使用它:

<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.

在您的示例中,您假设React导入的相对路径和硬编码到image标签中的图像源是相同的,但实际上却不是.

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.

这篇关于反应导入文件夹导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆