我一直在尝试导入外部库(谷歌地图)以便在 React 组件中使用它
索引.html file
<div id="app"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY_GOES_HERE&callback=initMap" async defer>
反应文件
componentDidMount() {
this.map = new google.maps.Map(this.refs.map, {
center: {lat: this.props.lat, lng: this.props.lng},
zoom: 8
});
}
render() {
return <div>
<p>I am a map component</p>
<div id="map" ref="map"/>
</div>
}
我得到的错误是:
未捕获的引用错误:谷歌未定义
我已经尝试了一切,但似乎没有任何效果。如何从组件内的脚本访问变量?
这只是一个示例,请不要告诉我使用 React Google Maps 的 NPM 包之一。
谢谢,
哈里斯
聚会有点晚了,但我也遇到了这个问题,对我来说,这是由 eslint 引起的。要禁用它只需添加评论/*global google*/
上面声明变量的地方,它应该可以工作,例如
componentDidMount() {
/*global google*/ // To disable any eslint 'google not defined' errors
this.map = new google.maps.Map(this.refs.map, {
center: {lat: this.props.lat, lng: this.props.lng},
zoom: 8
});
}
render() {
return <div>
<p>I am a map component</p>
<div id="map" ref="map"/>
</div>
}
您还可以使用 window 对象进行调用:
componentDidMount() {
/* Use new window.google... instead of new google... */
this.map = new window.google.maps.Map(this.refs.map, {
center: {lat: this.props.lat, lng: this.props.lng},
zoom: 8
});
}
render() {
return <div>
<p>I am a map component</p>
<div id="map" ref="map"/>
</div>
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)