我正在尝试在需要时以编程方式添加 google api 脚本。但是,我收到一个错误,即未定义 google。我可以看到脚本是在正文标记结束之前添加的。
之前我在 index.html 文件中加载了脚本,但是,我现在在应用程序的其他地方创建了一个不同的组件,它需要自己的脚本,因为它有不同的 api 密钥。因此,我不得不从 index.html 中删除该脚本,因为它为多次使用该脚本提供了一个例外。现在我想在加载组件时添加它。
主要组件请参考以下代码:
import React from 'react';
import { Button } from 'reactstrap';
import CitySuggestionBar from './CitySuggestionBar';
export default class Destination extends React.Component{
componentDidMount(){
this.renderScript();
}
renderScript = () => {
loadScript('https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places');
}
showPlaceDetails(place) {
let city = place.address_components[0].long_name.toString();
try{
city+= '+' + place.address_components[2].long_name.toString();
}catch(e){}
city = city.replace(/\s/g, "+");
sessionStorage.setItem('city', city);
console.log(city);
}
redirect = () =>{
sessionStorage.getItem('city') ? this.props.history.push("/hotels") : alert('Please select a city first');
}
render(){
return(
<div className="location-search-container">
<div className="location-search-wrapper">
<h1>Search for a city...</h1>
<CitySuggestionBar onPlaceChanged={this.showPlaceDetails.bind(this)} />
<Button onClick={this.redirect} className="btns" to="/hotels" color="primary">Proceed</Button>
</div>
</div>
);
}
}
const loadScript = (url) => {
const index = window.document.getElementsByTagName('script')[0];
const script = window.document.createElement('script');
script.src=url;
index.parentNode.insertBefore(script, index);
}
以下是使用谷歌地图的组件的代码,它是上述主要组件的子组件:
import React from "react";
/* global google */
export default class CitySuggestionBar extends React.Component {
constructor(props) {
super(props);
this.autocompleteInput = React.createRef();
this.autocomplete = null;
this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
}
componentDidMount() {
this.autocomplete = new window.google.maps.places.Autocomplete(this.autocompleteInput.current,
{"types": ['(cities)']});
this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
}
handlePlaceChanged(){
const place = this.autocomplete.getPlace();
this.props.onPlaceChanged(place);
}
render() {
return (
<input ref={this.autocompleteInput} id="autocomplete" placeholder="Search"
type="text"></input>
);
}
}
请帮忙!提前致谢。