如何在React项目中加载Google Places JS API库?

坏程序员

我正在使用“ 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'));

这是行不通的,我也尝试过直接将其加载到组件中(这似乎不正确):

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>
        );
    }
}

使用这些方法,我不断收到“必须加载Google Maps JavaScript API库”错误,并且我查看了文档,它没有指定标记的放置位置,只是将其放置在某个位置。

uneet7

我在我的一个项目中用过这种方式

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
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章