【问题标题】:Cant load images dynamically imported with webpack-image-loader and called from a JSON file无法加载使用 webpack-image-loader 动态导入并从 JSON 文件调用的图像
【发布时间】:2017-11-04 13:03:46
【问题描述】:

我正在尝试从 JSON 文件动态加载一些图像,我正在使用 webpack-image-loader 并做出反应。

我为此使用了几个 png,当我将变量名放在花括号内时,它就起作用了:

import gratuita from 'images/gift-50.png';

<img src={gratuita} className="pool-icons"/>

但是当我尝试在 JSON 文件的帮助下执行此操作时,问题就来了。

我在 webpack-image-loader 的帮助下按如下方式导入我的图片 (png):

import Baseball from 'images/BaseballBall-50.png';

然后我调用我的图像并使用 JSON 属性调用正确的文件,如下例所示:

<img src={sport.name} className="pool-icons"/>

JSON 文件具有以下数据结构:

"sport": {
        "id": 4,
        "name": "Baseball"
      },

然后,当调用 img 时,图像不显示,并且 src 文件没有将变量解析为 src 路由,而是得到了变量的名称,如下所示: the image don't show up,

我已经尝试过 eval() 但它不起作用,它会抛出这个错误:

Uncaught (in promise) ReferenceError: Baseball is not defined
at eval (eval at DisplaySport (eval at <anonymous> (output.js:5211)), <anonymous>:1:1)
at DisplaySport (eval at <anonymous> (output.js:5211), <anonymous>:247:13)
at eval (eval at <anonymous> (output.js:7605), <anonymous>:306:16)
at measureLifeCyclePerf (eval at <anonymous> (output.js:7605), <anonymous>:75:12)
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (eval at <anonymous> (output.js:7605), <anonymous>:305:14)
at ReactCompositeComponentWrapper._constructComponent (eval at <anonymous> (output.js:7605), <anonymous>:280:21)
at ReactCompositeComponentWrapper.mountComponent (eval at <anonymous> (output.js:7605), <anonymous>:188:21)
at Object.mountComponent (eval at <anonymous> (output.js:1396), <anonymous>:46:35)
at ReactDOMComponent.mountChildren (eval at <anonymous> (output.js:7917), <anonymous>:238:44)
at ReactDOMComponent._createInitialChildren (eval at <anonymous> (output.js:7629), <anonymous>:697:32)

在此先感谢,我被困在这部分,如果社区能提供一些帮助会很好。

【问题讨论】:

  • 你不应该给src的图像而不是sport的名称
  • 这就是问题所在,src PATH 位于名为 sport 的变量中

标签: javascript json image reactjs webpack


【解决方案1】:

尝试使用条件来检查运动名称是否与棒球匹配,

const Baseball = "https://s-media-cache-ak0.pinimg.com/originals/20/56/e1/2056e16bbc03d5eb41b4761356a8411b.jpg"

const sport={
  id: "1",
  name: "Baseball"
}

class App extends React.Component{
  render(){
    const name = sport.name
    return(
      <div>
        {sport.name === "Baseball" && <img src={Baseball} />}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

【讨论】:

  • 这听起来很公平,我必须构建一个 switch 语句,或者类似的东西来控制不同的变量,因为有 8 种运动。
  • 我终于用一个 switch 语句解决了这个问题,它可以捕获每个 sport.name,需要编写更多代码,但它工作得很好。谢谢
猜你喜欢
  • 2019-01-03
  • 2018-11-14
  • 2017-06-06
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 2019-04-28
  • 2020-04-17
相关资源
最近更新 更多