【问题标题】:React set image src to a dynamic path [duplicate]将图像 src 设置为动态路径 [重复]
【发布时间】:2018-12-09 20:46:38
【问题描述】:

所以我想做的是从 JSON 文件中读取 image-src。 在 JSON 文件中,我有这样的内容:

{
   posts:[
           {"img": "../images/a.png"},
           {"img": "../images/b.png"},

           //and more... 
         ]

}

然后我尝试在 react 中使用这些路径作为图像 src:

import data from '../posts.json';

<img src={require(data.posts[0].img)}/>

这不起作用,我收到此错误:错误:找不到模块“。”。 有什么方法可以让我完成这项工作吗?

【问题讨论】:

标签: javascript reactjs image src


【解决方案1】:

你不应该在那里使用require。

<img src={ data.posts[0].img }/>

【讨论】:

  • 我的解决方案没有任何错误,但图像没有显示。在chrome调试器中看到路径写对了,但是没有显示图片,这和webpack有关系。将 require 与静态路径一起使用时,它可以工作,但不能与动态路径一起使用。
猜你喜欢
  • 2021-12-06
  • 2019-10-24
  • 1970-01-01
  • 2018-11-30
  • 2020-03-05
  • 2023-04-04
  • 2023-03-20
  • 1970-01-01
  • 2021-05-17
相关资源
最近更新 更多