首页 > 解决方案 > React 中的图像:是否可以使用来自导入对象的字符串作为图像的源路径?

问题描述

关于在 React 中使用图像的问题!

导入图片然后使用它可以工作:

import photo from "../img/profilephoto.jpg"

<img src={photo} />

使用 props 作为 require() 中的源代码:

<img src={require(`../img/${this.props.img}`)} />

但是导入一个对象(带有更多对象),然后使用导航来获取一个字符串,是行不通的!

import text from "../text" // This is the object wich contains more objects

<img src={require(`../img/${text.contact.photo}`)} />

错误,因为“未定义文本”。

我一直在互联网上寻找答案,但找不到导入对象的解决方案。是否可以使用导入对象中的键/值作为 img 的路径源,而 img 本身之前没有导入?

标签: imagereactjs

解决方案


问题已经解决了!

我在 text.js 中有这样的内容;只是对象:

export default {

  header: {
    key: "value,
    key: "value",
    photo: "./img/photo.jpg"
},

  footer: {
  ...and so on...
  }

}

在组件中我有这个:

import text from "../text" // This is the object wich contains more objects

<img src={require(`../img/${text.contact.photo}`)} />

为了使 require() 起作用,需要知道照片。所以我在 text.js 中改成了这个:

*import photo from "./img/photo.jpg"* //This import is new

export default {

  header: {
    key: "value,
    key: "value",
    photo: *photo* //Use the imported phto instead of writing the file path
},

  footer: {
  ...and so on...
  }

}

在组件中:

<img src={text.contact.photo}/> //Using the text.js with the objects

现在它起作用了!

感谢您的反馈!


推荐阅读