繁体   English   中英

从JSON源导入图像(create-react-app)

[英]Import image from json source (create-react-app)

我有一些带有数据的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指定了哪个本地补丁?

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

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

确保从正确的路径加载。 您的照片未位于assets/anotherpic.png ,也许您应该从绝对路径./assets/anotherpic.png

如果您使用Webpack v4,是否尝试使用require.context()

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

请参阅webpack文档中的源代码

您的代码可以是这样的:

data.json

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

file.js

const pathToAssets = require.context('assets/');

...

render() {
  return (
     data.map((item) => (
       <img src={pathToAssets(item.image)} />
     ))
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM