Material-ui - Google自动填充地址

Azi*_*han 6 reactjs material-ui

我在我的React应用程序中使用Material-Ui,我正在尝试将地址的输入谷歌自动完成添加到我的表单中.

这是我的问题,我找到了这个库https://github.com/ErrorPro/react-google-autocomplete,它集成了谷歌地图API的地方,但输入看起来像最基本的输入,即0风格.

现在我的代码看起来像这样:

<Autocomplete
onPlaceSelected={(place) => {
    console.log("Place selected", place);
}}
types={['address']}
/>
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常并打印地址,简单的问题是输入具有默认的外观和感觉,我希望它具有材料-ui.

我也查看了这个库https://github.com/ydeshayes/googlePlaceAutocomplete,这似乎正是我想要的,但我无法使它工作,似乎没有太多记录.所以我试着编写这样的代码:

<GooglePlaceAutocomplete 
    onChange={this.onAutoCompleteInputChangeFct.bind(this)}
    onNewRequest={this.onClickLocationFct.bind(this)}
    name={'location'}
/>
Run Code Online (Sandbox Code Playgroud)

但是使用这段代码我得到了我的输入,但是当我输入建议时,它似乎无法正常工作.

所以我的问题是:有没有办法将自动完成组件从material-ui包装到TextField元素中?

Jef*_*oud 1

简而言之,您获取对<input />由 渲染的 DOM 元素的引用,然后在 componentDidMount() 中像平常一样TextField执行操作。google.maps.new places.Autocomplete()Autocomplete'splace_changed事件中,您可以对此执行一些操作,例如将其传递给 Redux 操作或由父级提供的回调/处理程序(例如 onPlaceChanged)

这是一个 jsFiddle,添加了一点 CSS,使其看起来更漂亮。它假设 Google Place API 已加载到浏览器中: https: //jsfiddle.net/e0jboqdj/3/

class LocationSearchBox extends React.Component {
  componentDidMount() {
    if (typeof google === 'undefined') {
      console.warn('Google Places was not initialized. LocationSearchBox will not function.');
      return;
    }

    const { country, onPlaceChanged } = this.props;
    const { places } = google.maps;

    let options;

    if (country) {
      options = {
        componentRestrictions: { country }
      };
    }

    const input = this.locationSearch;

    input.setAttribute('placeholder', '');

    if (!input._autocomplete) {
      input._autocomplete = new places.Autocomplete(input, options);

      input._autocomplete.addListener('place_changed', () => {
        onPlaceChanged && onPlaceChanged(input._autocomplete.getPlace());
      }.bind(input._autocomplete));
    }
  }

  render() {
    return (
      <span>
        <TextField ref={ref => (this.locationSearch = ref.input)} hintText="Search nearby" />
      </span>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)