如何在 React 应用程序中更新 google 地图 api 输入字段的状态

How to get the state updated of input field of google map api in React app

根据google map api的官方文档, 我试图按照以下方式在我的 React 应用程序中实现自动完成搜索 input

import React, { Component } from 'react';

export class App extends Component {
    state = {
        location: ''
    };

    handleChange = (e) => {
        this.setState({ location: e.target.value });
    };
    render() {
        function initAutocomplete() {
            var input = document.getElementById('pac-input');
            var searchBox = new window.google.maps.places.SearchBox(input);
        }
        initAutocomplete();
        return (
            <input
                defaultValue={this.state.location}
                onChange={this.handleChange}
                id="pac-input"
                className="controls"
                type="text"
                placeholder="Search your College"
            />
        );
    }
}

export default App;

我设法让它正常工作。但是,我看到的唯一问题是,每当我 select/click 自动完成选项时,输入栏的值都会更新为所选地址,但不会更新状态。 您可以查看此 short video demo 并请建议我应该做哪些更改才能使状态管理正常工作?

这里的问题是你只是在监听输入的 onChange 事件,而不是自动完成的 places_changed 事件,所以输入的 onChange 函数不会 运行 当您 select 地点建议自动完成列表中的一个地点时。尝试按如下方式修改您的代码:

import React, { Component } from "react";

export class App extends Component {
  state = {
    location: ""
  };

  componentDidMount() {
    const app = this;
    function initAutocomplete() {
      var input = document.getElementById("pac-input");
      var searchBox = new window.google.maps.places.SearchBox(input);
      searchBox.addListener("places_changed", function() {
        app.setState({ location: document.getElementById("pac-input").value });
      });
    }
    initAutocomplete();
  }

  handleChange = e => {
    this.setState({ location: e.target.value });
  };

  render() {
    return (
      <input
        defaultValue={this.state.location}
        onChange={this.handleChange}
        id="pac-input"
        className="controls"
        type="text"
        placeholder="Search your College"
      />
    );
  }
}

export default App;