三种方式:
1. 直接加载public 目录下的index.html中
直接在public 下的html文件下 加
2. 使用 react-load-script 插件动态引入
npm 安装
npm install react-load-script
使用
import React from 'react';
import Script from 'react-load-script';
class DynamicScriptExample extends React.Component {
constructor(props) {
super(props);
this.state = {
scriptStatus: 'no'
}
}
handleScriptCreate() {
this.setState({ scriptLoaded: false })
}
handleScriptError() {
this.setState({ scriptError: true })
}
handleScriptLoad() {
this.setState({ scriptLoaded: true, scriptStatus: 'yes' })
}
render() {
return (
<>
onCreate&#61;{this.handleScriptCreate.bind(this)}
onError&#61;{this.handleScriptError.bind(this)}
onLoad&#61;{this.handleScriptLoad.bind(this)}
/>
动态脚本引入状态&#xff1a;{this.state.scriptStatus}
>
);
}
}
export default DynamicScriptExample;
3. 自己用脚本在 react DOM渲染前&#xff0c;强制插入。。
大概意思如下
export default function getAMap() {
var isLoaded &#61; true
return new Promise(function (resolve, reject) {
if (isLoaded) {
window.AMap.plugin([&#39;AMap.MouseTool&#39;, &#39;AMap.PolyEditor&#39;], () &#61;> {
resolve(window.AMap)
})
return
}
var script &#61; document.createElement(&#39;script&#39;)
script.type &#61; &#39;text/Javascript&#39;
script.async &#61; true
script.src &#61; &#39;http://webapi.amap.com/maps?v&#61;1.4.3&key&#61;key&callback&#61;$$$maptcinit&plugin&#61;AMap.MouseTool&#39;
// script.onload &#61; resolve
script.onerror &#61; reject
script.onload &#61; function () {
isLoaded &#61; true
resolve(window.AMap)
}
document.head.appendChild(script)
})
}