谢谢阮成。就像google
现在在全局范围内我使用window.google
.
import React, { Component } from 'react';
import scriptLoader from 'react-async-script-loader';
class Map extends Component{
constructor(props) {
super(props);
}
componentWillReceiveProps({isScriptLoadSucceed}){
if (isScriptLoadSucceed) {
var markers = [];
var map = new window.google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 37.7749300, lng: -122.4194200}
});
}
else{
alert("script not loaded")
}
}
render(){
return(
<div>
<div id="map" style={{height: "600px"}}></div>
</div>
)
}
}
export default scriptLoader(
["https://maps.googleapis.com/maps/api/js?key= APIKEY"]
)(Map)
使用 react hook 我们还可以加载外部脚本
https://usehooks.com/useScript/
//useScript custom hooks from the site
let cachedScripts = [];
function useScript(src) {
// Keeping track of script loaded and error state
const [state, setState] = useState({
loaded: false,
error: false
});
useEffect(
() => {
// If cachedScripts array already includes src that means another instance ...
// ... of this hook already loaded this script, so no need to load again.
if (cachedScripts.includes(src)) {
setState({
loaded: true,
error: false
});
} else {
cachedScripts.push(src);
// Create script
let script = document.createElement("script");
script.src = src;
script.async = true;
// Script event listener callbacks for load and error
const onScriptLoad = () => {
setState({
loaded: true,
error: false
});
};
const onScriptError = () => {
// Remove from cachedScripts we can try loading again
const index = cachedScripts.indexOf(src);
if (index >= 0) cachedScripts.splice(index, 1);
script.remove();
setState({
loaded: true,
error: true
});
};
script.addEventListener("load", onScriptLoad);
script.addEventListener("error", onScriptError);
// Add script to document body
document.body.appendChild(script);
// Remove event listeners on cleanup
return () => {
script.removeEventListener("load", onScriptLoad);
script.removeEventListener("error", onScriptError);
};
}
},
[src] // Only re-run effect if script src changes
);
return [state.loaded, state.error];
}
用法
//App.js
import React from "react";
import ReactDOM from "react-dom";
import { useState, useEffect } from "react";
function App() {
const [loaded, error] = useScript(
"https://maps.googleapis.com/maps/api/js?key=API_KEY"
);
useEffect(() => {
if (loaded) {
new window.google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: { lat: 37.77493, lng: -122.41942 }
});
}
}, [loaded]);
return (
<div>
<div>
Script loaded: <b>{loaded.toString()}</b>
</div>
<div id="map" style={{ height: "600px" }} />
</div>
);
}