image - 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 本身之前没有导入?
解决方案
问题已经解决了!
前
我在 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
现在它起作用了!
感谢您的反馈!
推荐阅读
- c# - WPF数据网格显示字符串
- regex - 删除特定字符后的其余行
- db2 - 使用 CLI SQLDriverConnect 的隐式本地连接(无密码)失败并出现 SQL30082N 原因 3 PASSWORD MISSING
- rust - 结构方法作为 FFI 回调
- sql-server - 请帮助进行分组
- css - 车把内联css
- java - 关于 SonarQube 和 Active Directory 之间的简单 Ldap 连接
- c++ - 使用 make 文件将 c++ 代码与 ffi 绑定以颤振
- python - Python中缺少运算符的计算器
- google-apps-script - 您如何仅向 Google 电子表格中的工作表所有者授予编辑权限?