javascript - react : How can I dynamically render images mapping through a list?

标签 javascript json reactjs

我正在尝试映射对象数组。

我的 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'} />;
}

参见:

https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#using-the-public-folder

关于javascript - react : How can I dynamically render images mapping through a list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309015/

相关文章:

javascript - addComponentAsRefTo(...) : Only a ReactOwner can have refs - Error in Form with Select List

javascript - 在带有图例的引导模式中显示 donut /饼图

python - AWS Lambda 函数在 python 中误解了事件字典?

javascript - Jquery从json中获取值到select中

reactjs - 使用 mui-datatable 动态添加新列

reactjs - 增强react-select到material-ui的布局集成

javascript - 用 JavaScript 模拟 cut 函数?

javascript - 从已经包含动画的文件渲染和动画化 SVG

javascript - 禁用基于类的选择元素选项

android - JSON 字符串数组(无对象),提取数据