关于在 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/