我正在使用React,我想使用只能作为URL检索的包。在HTML中,使用script标签很容易导入,但是如何导入到JavaScript文件呢?
我想要的是将其转换
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
变成这样
import 'https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true'
答案 0 :(得分:2)
基于您在HTML中直接导入评论时的评论:
它抛出一个错误,表明该脚本的对象不是 定义
我认为这里最好的方法是不要尝试将js导入另一个js文件中,而应使用React google maps库,这样您就不会遇到这些问题。
尝试一下,让我们知道。
这个答案的原因是,即使您通过将另一个js文件添加到自己的js文件中来使脚本正常工作,Google Maps api js也会做更多的事情,这会给您带来React中的麻烦和问题(例如您现在就拥有了),并且此库已经解决了这些问题。
阅读at the official documentation,看看它是否对您有用。
示例
使用该库here有一个很好的教程和非常基本的示例。
使用经度和纬度的示例(摘自本教程):
const GoogleMapExample = withGoogleMap(props => (
<GoogleMap
defaultCenter = { { lat: 40.756795, lng: -73.954298 } }
defaultZoom = { 13 }
>
</GoogleMap>
));
return(
<div>
<GoogleMapExample
containerElement={ <div style={{ height: `500px`, width: '500px' }} /> }
mapElement={ <div style={{ height: `100%` }} /> }
/>
</div>
);
替代库
或者,您可以使用此库,因为它是另一个用于渲染Google地图的反应库。
您也可以在this tutorial中关注此库。
这些库有很多支持者和明星,这意味着您始终可以依靠更新和有用的信息。