【问题标题】:How to load the images from JSON object using react?如何使用 React 从 JSON 对象加载图像?
【发布时间】:2019-06-17 20:14:12
【问题描述】:

我已经创建了对象数组,并在其中提供了图像路径。我无法使用 react 从对象数组中加载图像,并且出现“找不到模块”之类的错误。过去 2 天我一直在解决这个问题,请任何人帮助我解决这个问题或给我对下一步做什么提出了一些建议。我分享了下面的代码sn-p:

    state = {
        data: [
          {
            id: 1,
            name: "Mattel Uno Playing Card Game",
            imagePath: "../images/lenovo-p50.jpg"
          },
          {
            id: 2,
            name: "Hot Wheels Car",
            imagePath: "../images/lenovo-p51.jfif"
          },
          {
            id: 3,
            name: "Centy Toys Ambassador Car",
            imagePath: "../images/lenovo-p50.jpg"
          }
        ]
      };

      render() {
        return (
          <div>
            <table>
              <thead>
                <tr>
                  <th>Item Name</th>
                  <th>Item images</th>
                </tr>
              </thead>
              <tbody>
                {this.state.data.map((ele, i) => {
                  return (
                    <tr key={ele.id}>
                      <td>{ele.name}</td>
                      <td>
                        <img src={require(ele.imagePath)} width="200" />
                      </td>
                    </tr>
                  );
                })}
                <tr />
              </tbody>
            </table>
          </div>
        );
      }

如何在 react 中加载对象数组中的图片?

【问题讨论】:

    标签: javascript html json ajax reactjs


    【解决方案1】:

    你不需要在 src 中添加require。当使用相对路径时,它将转到服务器中可用的图像,但是当给定 url 时,图像将被加载。你可以找到更多信息here

    当使用 src 作为/images/lenovo-p50.jpg 时,它将转换为localhost:3000/images/lenovo-p50.jpg

    【讨论】:

      猜你喜欢
      • 2019-03-06
      • 1970-01-01
      • 2021-03-17
      • 2016-10-31
      • 2013-08-16
      • 2018-11-06
      • 2021-06-06
      • 1970-01-01
      • 2016-10-23
      相关资源
      最近更新 更多