React:如何引用require中的图片网址

时间:2017-09-23 23:06:56

标签: reactjs redux

我有一个数据文件api,其中包含一堆本地存储的图像

   const url =[
          { title:img1,
            img_src="./img/img1.png"
          },
          { title:img2,
            img_src="./img/img2.png"
          },
          { title:img3,
            img_src="./img/img3.png"
          }
      ]

使用react / redux我将url状态作为props传递给我的react组件。接下来我想通过使用require

在我的组件中显示它们
<img src=require(?)/>

这里的语法是什么?我已经使用了es6模板字符串${this.props.urls.img_src},但它抛出了无法解析路径的错误。我试图要求(“./ img / img1.png”)只是为了测试以排除破碎的路径并且它起作用。但如果你使用道具引用它仍然无法工作。

解决方案

经过研究,感谢Rei Dien的输入,我现在可以通过使用上下文需要使用require中的变量

<img src={require("./img/"+this.props.img_src)}/>

2 个答案:

答案 0 :(得分:0)

因为require仅在节点上的构建过程中以静态模式工作,因此请按照以下步骤操作。

1)获取所有图片网址并将其存储在javascript文件中 所以

// imageURLs.js

import image1 from "path_to_image_file_1";
import image2 from "path_to_image_file_2";
import image3 from "path_to_image_file_3";/**do like this for all images stored locally, image1, image2,.. are the image identifiers(title in your case) you would get in api call**/
export const urls = {image1, image2, image3};

//图像使用文件

读取api的标识符和

import imageURLs from './imageURLs.js';
<img src={imageURLs[image_id_from_api]}/>

答案 1 :(得分:0)

由于你在道具中传递了网址,你可以这样做:

this.props.url.map(n => {
 return (
   <img src={n.img_src}/>
 )
})

这将覆盖所有图像。