Bad*_*mer 4 javascript google-places-api reactjs google-places-autocomplete
我正在使用'react-places-autocomplete' 库。我知道我必须使用我的密钥加载 API。我不知道将密钥的脚本放在哪里,以便程序能够运行。
我看到一个 StackOverflow 页面,有人说在 index.js 中静态加载它,我试过:
import 'react-places-autocomplete';
...
ReactDOM.render(
<div>
<BrowserRouter>
<App />
</BrowserRouter>
<script src="https://maps.googleapis.com/maps/api/js?
key=MY_KEY&libraries=places"></script>
</div>
, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
这不起作用,我也尝试将它直接加载到组件中(这似乎不正确):
class My_Component extends React.Component {
...
render() {
return (
<div>
<script src="https://maps.googleapis.com/maps/api/js?
key=MY_KEY&libraries=places"></script>
<PlacesAutocomplete
value={this.state.address}
onChange={this.handleChange}
onSelect={this.handleSelect}
>
....
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
使用这些方法,我不断收到“必须加载 Google Maps JavaScript API 库”错误,并且我查看了文档,它没有指定标签需要放置的位置,只是需要在某个地方。
我在我的一个项目中以这种方式使用它
class PlacesAutocomplete1 extends React.Component {
constructor(props) {
super(props);
this.state = {
googleMapsReady: false,
};
}
componentDidMount() {
script is loaded here and state is set to true after loading
this.loadGoogleMaps(() => {
// Work to do after the library loads.
this.setState({ googleMapsReady: true });
});
}
componentWillUnmount() {
// unload script when needed to avoid multiple google scripts loaded warning
this.unloadGoogleMaps();
}
loadGoogleMaps = callback => {
const existingScript = document.getElementById("googlePlacesScript");
if (!existingScript) {
const script = document.createElement("script");
script.src =
"https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places";
script.id = "googleMaps";
document.body.appendChild(script);
//action to do after a script is loaded in our case setState
script.onload = () => {
if (callback) callback();
};
}
if (existingScript && callback) callback();
};
unloadGoogleMaps = () => {
let googlePlacesScript = document.getElementById("googlePlacesScript");
if (googlePlacesScript) {
googlePlacesScript.remove();
}
};
render() {
if (!this.state.googleMapsReady) {
return <p>Loading</p>;
}
return (
// do something you needed when script is loaded
}
Run Code Online (Sandbox Code Playgroud)