javascript - 如何在 React 中正确扩展从外部站点加载的 JS 类

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

我需要在我的应用程序中做一些事情。 1.加载Google map API 2. 初始化我的 map 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'未定义之类的错误。如果我尝试将其放入 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) 但是,该组件在顶部导入 Map,而后者又导入 ImageOverlay,这当然会失败,因为 google 尚未定义。

最佳答案

好吧,这就是我最终解决这个问题的方法:

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 作为 prop 传递给 Map 组件。

关于javascript - 如何在 React 中正确扩展从外部站点加载的 JS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45106908/

相关文章:

javascript - 将 Immutable.js map 列表转换为列表列表,然后将其用作谷歌图表的数据

javascript - 垂直添加元素时如何防止背景图像在移动浏览器上缩放?

css - 我如何创建样式元素并附加到 React 中的头部?

javascript - 单击矩形数组的 Loop 中的 Listeners -- 关闭

javascript - for 循环内的 async.waterfall 逃脱了 for 循环

javascript - 如何使用 Chrome DevTools 检查 BroadcastChannel?

javascript - 如何在 typescript 中分隔具有特定数组前缀的对象数组

image - 是否可以使用 javascript 更改 google.maps.GroundOverlay 的图像?

javascript - 具有标准样式的 Google map 自定义按钮

Javascript正则表达式匹配 "1v1"或 "30v30"等