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

标签 javascript json image reactjs webpack

我正在尝试从 JSON 文件动态加载一些图像,我正在使用 webpack-image-loader 和 React。

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

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

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

但是当我尝试借助 JSON 文件来完成此操作时,问题就出现了。

我正在导入我的图像(png),如下所示,并使用 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)

预先感谢,我陷入了这一部分,如果社区能提供一些帮助,那就太好了。

最佳答案

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

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>

关于javascript - 无法加载使用 webpack-image-loader 动态导入并从 JSON 文件调用的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44340435/

相关文章:

javascript - 无法从字符串集合中找到 href 标签

javascript - NODE 中同时 GET 和 POST 请求

javascript - 检查用户是否已收到并邀请参加 10 天内发生的事件。 (罗尔)

json - 拒绝对 Nginx 中特定路径的所有 json 文件的请求

css - 右栏中的文字低于左栏中的图像

Javascript 调用函数乱序

java - 使用深层数组创建 JSON 文件

javascript - JSON.parse 的问题

jquery - 这种代替 AJAX 请求图像的方法有多糟糕?

ios - 如何在 Button 内将 cornerRadius 设置为 UIImage?