react.js - 如何在React组件中引入百度地图API
本文介绍了react.js - 如何在React组件中引入百度地图API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
引入了百度API,但是无法引入,代码如下:
...
componentWillMount() {
const script1 = document.createElement("script");
script1.src = "http://api.map.baidu.com/api?v=2.0&ak=xxx";
script1.type = "text/javascript";
script1.async = true;
document.head.appendChild(script1);
const script2 = document.createElement("script");
script2.async = true;
script2.type = "text/javascript";
script2.src = "http://api.map.baidu.com/library/LuShu/1.2/src/LuShu_min.js";
document.head.appendChild(script2);
}
...
componentDidMount() {
_.extend(BMapLib.LuShu.prototype, {
// do something
})
}
...
error: BMapLib is not defined
求解
2016.12.22更新我的解决方案
在入口html判断需要引入API的页面是否需要引入百度API˜
example:
if (location.hash.indexOf('driver_map_found') > -1) {
document.write('<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=uRIgQnOKFQ77LLvuI9WzNgri"><\/script>');
document.write('<script type="text/javascript" src="http://api.map.baidu.com/library/LuShu/1.2/src/LuShu_min.js"><\/script>');
}
解决方案
I think:
It's necessaty to check whether the script is included or not. u can check the global variables window.xxx
.it's definitely not included:
if (window.xxx === 'undefined') {
// include the script
}
u should put the script in componentDidMount
or componentDidUpdate
.the DOM must be ready in these two stages of the reactjs life circle, .
The thing is that add the onload
handler to the script1
u created,it'll be called right after the script is loaded.
script1.onload = function() {
// do what u want to initialize the third part module
}
非react插件,默认你的dom是准备好的,在引入这些插件的注意点就是DOM是否准备好
这篇关于react.js - 如何在React组件中引入百度地图API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文