【问题标题】:Material-ui - Google autocomplete addressMaterial-ui - 谷歌自动完成地址
【发布时间】:2017-04-25 07:52:56
【问题描述】:

我在我的 React 应用程序中使用 Material-Ui,我正在尝试在我的表单中添加一个输入 google 自动补全地址。

这是我的问题,我找到了这个库https://github.com/ErrorPro/react-google-autocomplete,它集成了 google maps API for places,但输入看起来像是最基本的输入,即 0 样式。

目前我的代码如下所示:

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

这段代码可以正常工作并打印地址,简单的问题是输入具有默认外观,我希望它具有material-ui。

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

<GooglePlaceAutocomplete 
    onChange={this.onAutoCompleteInputChangeFct.bind(this)}
    onNewRequest={this.onClickLocationFct.bind(this)}
    name={'location'}
/>

但是对于这段代码,我有我的输入,但是当我输入建议时,它似乎不起作用。

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

【问题讨论】:

  • 是的,我已经做到了。我正在尝试提取我对 jsFiddle 所做的事情。准备好后我会发布答案。
  • 你有没有找到一个很好的解决方案来使用 Material UI TextFields 和 Google Places 自动完成功能?除了手动实现自动完成之外,我还没有找到解决方案。

标签: reactjs material-ui


【解决方案1】:

简而言之,您获取由TextField 渲染的&lt;input /&gt; DOM 元素的引用,然后在componentDidMount() 中照常执行google.maps.new places.Autocomplete()。在Autocompleteplace_changed 事件中,您将执行一些操作,例如将其传递给 Redux 操作或由父级提供的回调/处理程序(例如 onPlaceChanged)

这是一个 jsFiddle,添加了一些 CSS 使其看起来不错。它假设 Google Places 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>
    );
  }
}

【讨论】:

  • 嗯,当我尝试执行您的代码时遇到问题:首先,我必须将“place_changed”函数更改为经典函数,而不是带有箭头的函数,并且当执行&lt;TextField ref={ref =&gt; (this.locationSearch = ref.input)} hintText="Search nearby" /&gt; 时,控制台告诉我 ref 是空的......你有什么想法吗?而且,当我在 Textarea 中输入文本时,控制台中出现错误提示 Unexpected batch number... 每次我在 Textarea 中输入时都会弹出
猜你喜欢
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 2013-03-23
  • 2017-09-16
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多