简体   繁体   English

将图像动态插入到 React 组件中

[英]Dynamic insertion of images into a React component

I'm trying to create a simple weather app.我正在尝试创建一个简单的天气应用程序。 It gets an API response where weather description is represented by some string, ie "clear sky".它得到一个 API 响应,其中天气描述由一些字符串表示,即“晴朗的天空”。 I've created js object corresponding that strings to icon's files paths which are in src/assets/images folder:我已经创建了 js object 对应于src/assets/images文件夹中图标文件路径的字符串:

const weatherIcons = {
  // ...
  "Heavy_Rain": "../assets/images/icons8-heavy-rain-96.png",
  // ...
}

I'm trying to dynamically display that icon in my component:我正在尝试在我的组件中动态显示该图标:

<img className="img-fluid" src={require(weatherIcons.Heavy_Rain)} />

And I got error:我得到了错误:

Error: Cannot find module '../assets/images/icons8-heavy-rain-96.png'错误:找不到模块“../assets/images/icons8-heavy-rain-96.png”

But it works perfectly if I use string directly as a require argument:但是如果我直接使用 string 作为require参数,它会完美地工作:

<img className="img-fluid" src={require("../assets/images/icons8-heavy-rain-96.png")} />

I use Parcel istead of Webpack to bundle project files.我使用 Parcel 而不是 Webpack 来捆绑项目文件。 And I didn't run Create React App, so I don't have Public folder in my project.而且我没有运行 Create React App,所以我的项目中没有 Public 文件夹。

What do I do to have my icons displayed eventually?我该怎么做才能最终显示我的图标?

This is happening at runtime:这发生在运行时:

require(weatherIcons.Heavy_Rain)

This happens at compile:这发生在编译时:

require("../assets/images/icons8-heavy-rain-96.png")

So you will need a public folder for dynamic or some public link with the image.因此,您将需要一个公共文件夹用于动态或与图像的一些公共链接。

If your homepage is set to "."如果您的主页设置为“。” and put the image in the public folder it should work.并将图像放在应该可以工作的公用文件夹中。

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

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