recommends two imported methods, of course, you can write a JS class (ES6 syntax) to dynamically insert JS into the page, and then introduce it in the React project.
first: use the plug-in react-load-script,. If you don't have it installed, you can use yarn add react-load-script or npm install react-load-script, to see which package management tool you use.
then you can insert the following code in JS, as you would with the React component.
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 (
<>
<Script
url="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"
onCreate={this.handleScriptCreate.bind(this)}
onError={this.handleScriptError.bind(this)}
onLoad={this.handleScriptLoad.bind(this)}
/>
<div>:{this.state.scriptStatus}</div>
</>
);
}
}
export default DynamicScriptExample;
the second is introduced directly in the index.html under the project / Public directory.
roughly means something like this
export default function getAMap() {
var isLoaded = true
return new Promise(function (resolve, reject) {
if (isLoaded) {
window.AMap.plugin(['AMap.MouseTool', 'AMap.PolyEditor'], () => {
resolve(window.AMap)
})
return
}
var script = document.createElement('script')
script.type = 'text/javascript'
script.async = true
script.src = 'http://webapi.amap.com/maps?v=1.4.3&key=key&callback=$$$maptcinit&plugin=AMap.MouseTool'
// script.onload = resolve
script.onerror = reject
script.onload = function () {
isLoaded = true
resolve(window.AMap)
}
document.head.appendChild(script)
})
}
what's wrong with the global situation? Wechat just recommends that you use global
to learn about createObjectUrl
.