React 中的图像 : is it possible to use a string from an imported object as the source path for an image?

标签 image reactjs

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

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

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

<img src={photo} />

在 require() 中使用 props 作为源是可行的:

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

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

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

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

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

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

最佳答案

问题解决了!

之前

我在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

现在可以了!!

感谢反馈!

关于React 中的图像 : is it possible to use a string from an imported object as the source path for an image?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310782/

相关文章:

jquery从img src而不是window.location.href获取变量

javascript - 双重渲染useEffect Reactjs

javascript - componentWillReceiveProps() 被触发但它没有获取 props

jquery - 使用 jQuery 使用单击图像的 url 更改背景图像

css - 输入类型 ="image"在 Chrome 中显示不需要的边框,在 IE7 中显示断开的链接

javascript - JavaScript 中的非确定性图像属性数据

html - CSS:在没有内容和/或固定尺寸的情况下显示背景图像?

javascript - 如何使用 nextjs 将静态网站部署到 AWS S3

javascript - 从另一个组件调用 React 组件的特定实例的方法

reactjs - React 路由器类型错误 : Cannot read property 'state' of undefined