我正在尝试映射对象数组。
我的 json 中 staff
中的每个数组元素都有一个 imgUrl
:
{
"home": {
...
"staff": [
{
...
"imgUrl": "../Images/Jon.JPG",
...
},
...
],
...
}
...
}
这被带入我的主 App.js
文件中
import data from './data.json';
并传递给组件:
<Home data={data.home} />
在家里我有:
let staff = this.props.data.staff.map((member, i) => {
return (
<Staff imgUrl={member.imgUrl} />
);
然后在 Staff
中我尝试加载图像:
<img src={this.props.imgUrl} alt={this.props.name} />
但是这不起作用,alt 会显示。我已检查是否将正确的字符串传递给 src,确实如此,但图像仍未加载。
如果我将 {this.props.imgUrl}
替换为 json 中存储的实际路径,则图像将加载。我已经对此进行了几个小时的搜索,但没有取得任何成果,也没有能够实现其他人用于解决类似问题的解决方案。
我使用 create-react-app 来启动这个项目。
编辑:好吧,我很愚蠢,我不久前复制了 Images 文件夹(它位于 src 中,移至公共(public)),但使用我的路径访问了 src 中的文件夹。我已将其更改为公共(public)版本,一切正常。感谢大家的帮助。
最佳答案
如果您没有将图像导入 JS 文件,即
import logo from './logo.png'; // Tell Webpack this JS file uses this image
您应该使用public
文件夹
render() {
// Note: this is an escape hatch and should be used sparingly!
// Normally we recommend using `import` for getting asset URLs
// as described in “Adding Images and Fonts” above this section.
return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}
参见:
关于javascript - react : How can I dynamically render images mapping through a list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309015/