React中的图像:是否可以使用来自导入对象的字符串作为图像的源路径? [英] Images in React: is it possible to use a string from an imported object as the source path for an image?

查看:60
本文介绍了React中的图像:是否可以使用来自导入对象的字符串作为图像的源路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关在React中使用图片的问题!

Question about using images in React!

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

Importing a pic and then using it works:

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

<img src={photo} />

使用props作为require()内的源工作

Using props as the source inside a require() works:

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

但是导入一个对象(包含更多对象),然后使用导航获取字符串是不可行的!

But importing an object (with more objects), and then using navigation to get a string, does not work!

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

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

由于未定义文本"而出错.

Error because "text is not defined".

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

I've looking for answer on the internet, but I can't find a solution for an imported object. Is it possible to use a key/value in an imported object as a path source for an img, where the img itself is not previously imported?

推荐答案

问题已解决!

之前

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

I had it like this in text.js; just objects:

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中更改为:

In order for the require() to work, the photo needs to be known. So I changed to this in the 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

现在它可以工作了!

感谢您的反馈!

这篇关于React中的图像:是否可以使用来自导入对象的字符串作为图像的源路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆