简体   繁体   English

错误:在 react.js 上找不到模块“./img.jpg”

[英]Error: Cannot find module './img.jpg' on react.js

在 react 的一个功能组件中,我试图使用来自 props 的图像的 URL 和代码<img src={require(productUrl).default}/> (这里的 productUrl 来自 props)但是有一个找不到模块的错误我还为 productUrl 做了一个控制台日志,它打印了预期值,当我在 require 中硬编码 url 的值时,它工作正常,但我不能使用硬编码值,因为 URL 来自 props

You do not need to use require within React Component.require在 React 组件中使用require Try to directly use your prop in the img src .尝试直接在img src使用您的道具 Something like this:像这样的东西:

<img src={productUrl} alt="my image"/>

Considering productUrl contains the correct url source for the image :)考虑到productUrl包含图像的正确url源 :)

Since, you have not added any code in the question.因为,您没有在问题中添加任何代码。 Hope this article would be useful as per your requirement from BetterProgramming.pub betterprogramming.pub/how-to-display-images-in-react希望这篇文章会按您的要求从有用BetterProgramming.pub betterprogramming.pub/how-to-display-images-in-react

UPDATE: After getting idea from Comment Sections After getting the codebase, I have fixed the issues with this.更新:从评论部分获得想法后获得代码库后,我已经解决了这个问题。

CodeSandBox Link: https://codesandbox.io/s/issuewithimage-qmkpg CodeSandBox 链接: https ://codesandbox.io/s/issuewithimage-qmkpg

Some of the major issue were:一些主要问题是:

  1. products array were wrongly exported as a function while we could directly export them and we do not need any function. products 数组被错误地导出为函数,而我们可以直接导出它们,我们不需要任何函数。
  2. Since you are using local images in this case we must make sure we place them in the public folder and do not use relative path (which leads to issues).So place all the images that you wish to use in public folder as I have done and use same names in your products array.由于在这种情况下您使用的是本地图像,因此我们必须确保将它们放置在公用文件夹中并且不使用相对路径(这会导致问题)。因此,将您希望使用的所有图像放在公用文件夹中,就像我所做的那样并在您的产品数组中使用相同的名称。
  3. Rest you may figure out from the code.休息一下,你可以从代码中找出来。 :D :D

CHEERS !!!干杯!!!

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

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