【问题标题】:React: How to reference an image url in requireReact:如何在 require 中引用图像 url
【发布时间】:2017-09-23 23:06:56
【问题描述】:

我有一个数据文件 api,其中有一堆图像 url 存储在本地

   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},但它会引发无法解析路径的错误。我试图 require("./img/img1.png") 只是为了测试以排除损坏的路径并且它有效。但是,如果您使用道具引用它,仍然无法正常工作。

解决方案

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

&lt;img src={require("./img/"+this.props.img_src)}/&gt;

【问题讨论】:

  • 使用新的导入。我相信它可以带一个变量,我不太确定 require 是否可以带一个变量。 2ality.com/2017/01/import-operator.html
  • 您好,谢谢您的回复。您的回答有点引导您找到解决方案。我研究了 require 接受变量,它通常会,但 webpack 只做静态字符串依赖,所以它无法解析路径。为了解决它我不得不做context require
  • 哦,我看到你正在使用 webpack。很高兴能帮上忙:)

标签: reactjs redux


【解决方案1】:

由于你在 props 中传递了 url,你可以这样做:

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

这将显示所有图像。

【讨论】:

  • 我尝试将其作为我的第一个选项,但它不起作用。它呈现 404 错误
【解决方案2】:

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

1) 获取所有图像 url 并将它们存储在 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]}/>

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多