我正在使用 React,我想使用一个只能作为 URL 检索的包。在 HTML 中使用脚本标签很容易导入,但是如何导入到 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 中导入时的评论:
It throws an error which says that the objects of the script aren't defined
我认为这里最好的方法是不要尝试在另一个 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>
);
替代库
或者,您可以使用这个库,因为它是另一个用于渲染谷歌地图的 React 库。
您也可以关注this tutorial有了这个图书馆。
这些图书馆有很多支持者和明星,这意味着您可以随时获得更新和有用的信息。
关于javascript - 有没有办法从 URL 导入脚本包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52929176/