【问题标题】:Trying to read images from .json file in create-react-app尝试从 create-react-app 中的 .json 文件中读取图像
【发布时间】:2018-11-28 20:36:15
【问题描述】:

我正在尝试将 .json 文件中的图像加载到我的组件中,但该图像未加载。

Someone looks to have solved it, but I don't know what he is talking about in terms of "branching"

  "Bumper": [{
      "id": 1,
      "productSquareId": "BumperStubby",
      "productImage": "bumper",
      "companyImage": "logo.png",
      "price": "$55.99"
    },

const image1 = ProductInformation.Bumper[0].companyImage;
<img  className = "MainImage" src ={image1}/>

我的图像与我的组件在同一个文件夹(组件)中。我在这里做错了什么?感谢您的宝贵时间。

【问题讨论】:

  • 你最后要关闭你的数组吗????
  • 是的。我只是给了一个sn-p。

标签: javascript reactjs


【解决方案1】:

看起来我解决了我的问题,但我的 .json 文件变成了 .js 文件。

&lt;img className = "MainImage" src ={bumper[0].productImage}/&gt;

export const bumper = [
  {
    id: 1,
    productSquareId: 'BumperStubby',
    productImage: require('./bumper1.png'),
    companyImage: require('./logo.png'),
    price: '$55.99',

  }
]

使用 .js 文件与使用 .json 文件有性能差异吗?

【讨论】:

  • 不错的一个。遵循你的逻辑,让它为我工作
【解决方案2】:

您是否尝试过在图片名称前加一个斜线 我想你可以在这里找到一些解决方案: Correct path for img on React.js

最快的方法是像这样使用 require:

<img  className = "MainImage" src ={require(image1)}/>

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 2019-01-10
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2019-05-10
    • 2020-07-31
    相关资源
    最近更新 更多