【问题标题】:Import image from json source (create-react-app)从 json 源导入图像 (create-react-app)
【发布时间】:2019-01-10 16:46:07
【问题描述】:

我有一些带有数据的 json,其中一个参数是带有图像的本地文件夹的路径:

// data.json
[
  {
    "id": 1,
     "image": "assets/somepic.png"
  },
  {
    "id": 2,
     "image": "assets/anotherpic.png"
  }
  // similar data goes there
]

然后我将这些数据导入到我的组件中

import data from "data.json"

我想通过这些数据进行映射:

render() {
  return (
     data.map((item) => (
       // Ofc it won't work if I just put {item.image} in src,
       // because we need to import image before use it
       // that's why I'm trying to use require
       <img src={require(item.image)} />
     ))
  )
}

但这行不通。 如何使用图像,在 json 数据中为 create-react-app 指定了哪个本地补丁?

请注意:应用程序不应被弹出。

【问题讨论】:

  • 代替地图,试试forEach
  • 不,它不起作用
  • 您还需要将 img 标签包装在 div 标签中。
  • 我为什么需要它?

标签: javascript reactjs create-react-app


【解决方案1】:

检查 create-react-app 是否已将 Webpack 配置为开箱即用地捆绑图像(.png 检查webpack.config.js)。如果是这样,如果assets 与组件位于同一文件夹中,您似乎只是缺少以“./assets/anotherpic.png”开头的相对路径。

【讨论】:

【解决方案2】:

确保从需要正确的路径加载。你的照片不在assets/anotherpic.png,也许你应该从绝对路径./assets/anotherpic.png加载

【讨论】:

    【解决方案3】:

    如果你使用Webpack v4,你有没有尝试使用require.context()

    它允许您传入要搜索的目录、指示是否也应搜索子目录的标志以及匹配文件的正则表达式。

    See the source into the webpack documentation

    你的代码可以是这样的:

    数据.json

    [
      {
        "id": 1,
         "image": "somepic.png"
      },
      {
        "id": 2,
         "image": "anotherpic.png"
      }
      // similar data goes there
    ]
    

    文件.js

    const pathToAssets = require.context('assets/');
    
    ...
    
    render() {
      return (
         data.map((item) => (
           <img src={pathToAssets(item.image)} />
         ))
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-20
      • 2023-03-17
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 2019-02-18
      • 2020-12-17
      • 2020-07-31
      相关资源
      最近更新 更多