我正在使用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'
最佳答案
根据直接导入html时的注释:
它抛出一个错误,指出脚本的对象不是
定义
我认为这里最好的方法是不要尝试将js导入到另一个js文件中,而是使用React google maps库,这样就不会遇到这些问题。
试试让我们知道。
这个答案的原因是,即使通过将另一个js文件添加到您自己的js文件中使脚本工作,google maps api js也会做更多的事情,这会给您带来麻烦和问题(就像您现在遇到的那样),并且这些问题已经由这个库解决了。
读一读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地图的react库。
google-map-react
您也可以使用此库跟踪this tutorial。
这些图书馆有很多支持者和明星,这意味着你可以随时依靠更新和有用的信息。