无法加载使用webpack-image-loader动态导入的图像,并从JSON文件调用

时间:2017-06-03 04:57:01

标签: javascript json image reactjs webpack

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

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

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

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

但是当我尝试在JSON文件的帮助下完成问题时,问题就出现了。

我正在导入我的图像(pngs),如下所示:webpack-image-loader的帮助,如下所示:

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)

在此先感谢,我已经陷入了这一部分,社区的帮助会很好。

1 个答案:

答案 0 :(得分:0)

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

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>