【问题标题】:How properly to extend a JS class loaded from an external site in React如何在 React 中正确扩展从外部站点加载的 JS 类
【发布时间】:2017-07-14 15:40:54
【问题描述】:

我需要在我的应用中做几件事。 1.加载谷歌地图API 2.初始化我的地图 3. 获取google变量的引用,并用它来做一个事件监听器并扩展它包含的ImageOverlay类

现在我正在使用this pattern,所以我可以通过window.google 引用google。然后在我的 initMap 中,我设置了一个事件监听器并执行 ```

ImageOverlay.prototype = new window.google.maps.OverlayView();

function ImageOverlay(bounds, image, map) {
    ...do constructory stuff
  }

  ImageOverlay.prototype.onAdd = function() {

    ...
  };

创建我需要的类(来自the G Maps docs)。我想将此代码移动到外部文件中,但我不知道如何清理它。我收到诸如'ImageOverlay' is not defined 之类的错误。如果我尝试将其变成 ES6 类(export default class ImageOverlay extends window.google.maps.OverlayView { 然后是 import ImageOverlay ...)它会失败,因为尚未定义 window.google。所以我的问题是,我怎样才能正确加载该类然后扩展它?如果我需要提供更多详细信息/澄清任何内容,请告诉我。 TIA。

替代问题:我使用react-async-script-loader 加载API:export default scriptLoader(['https://maps.googleapis.com/maps/api/js?key=whoop&callback=initMap&libraries=visualization'])(MapContainer) 但是,此组件在顶部执行import Map,然后执行import ImageOverlay,这当然失败了,因为@ 987654335@尚未定义。

【问题讨论】:

    标签: javascript reactjs google-maps-api-3 ecmascript-6


    【解决方案1】:

    好吧,这就是我最终解决它的方法:

    import scriptLoader from 'react-async-script-loader'
    class MapContainer extends Component {...}
    
    export default scriptLoader(['https://maps.googleapis.com/maps/api/js?key=mykey&libraries=visualization'])(MapContainer)
    
    ....
    
    class Map extends Component {
      componentDidMount() {
        var ImageOverlay = require('../Util/ImageOverlay.js').default;
    
    ...
    export default class ImageOverlay extends window.google.maps.OverlayView { ... }
    

    最大的事情是使用require(~).default(可以动态导入)而不是 React 文件顶部的导入。然后,您可以确保 window.google.maps 是可访问的,并且在加载 api 之前,该类不会尝试扩展它。您甚至可以将maps 作为道具传递给Map 组件。

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 2015-05-16
      • 2019-08-21
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      相关资源
      最近更新 更多