我需要在我的应用程序中做一些事情。
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/