首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >mui-places-autocomplete:如何订阅明文域事件?

mui-places-autocomplete:如何订阅明文域事件?
EN

Stack Overflow用户
提问于 2018-08-05 16:50:45
回答 2查看 575关注 0票数 0

我使用的是演示中解释的mui-places-autocomplete

代码语言:javascript
复制
import React from 'react'
import SomeCoolComponent from 'some-cool-component'
import MUIPlacesAutocomplete, { geocodeByPlaceID } from 'mui-places-autocomplete'

class Example extends React.Component {
  constructor() {
    super()

    // Setup your state here...
    this.state = { coordinates: null }

    this.onSuggestionSelected = this.onSuggestionSelected.bind(this)
  }

  onSuggestionSelected(suggestion) {
    geocodeByPlaceID(suggestion.place_id).then((results) => {
      // Add your business logic here. In this case we simply set our state with the coordinates of
      // the selected suggestion...

      // Just use the first result in the list to get the geometry coordinates
      const { geometry } = results[0]

      const coordinates = {
        lat: geometry.location.lat(),
        lng: geometry.location.lng(),
      }

      this.setState({ coordinates })
    }).catch((err) => {
      // Handle any errors that occurred when we tried to get geospatial data for a selected
      // suggestion...
    })
  }

  render() {
    // Your render logic here...
  }
}

export default Example

当用户选择一个建议时,这是有效的。但是当用户清除这个搜索框时,我们如何捕捉事件呢?

在以前的类似库中,我使用了类似的内容:handleChange,但它现在不起作用/使用这个库。

EN

回答 2

Stack Overflow用户

发布于 2018-08-05 19:59:19

自动建议组件在内部使用<TextField />组件。因此,您应该能够使用textFieldProps来管理输入字段上的事件。

请参阅source

票数 1
EN

Stack Overflow用户

发布于 2018-08-07 06:07:25

使用@dkulkarni的提示,我终于让它工作了。

代码语言:javascript
复制
import React, { Component } from 'react'
import GooglePlaceAutocomplete from 'mui-places-autocomplete'
import { geocodeByAddress } from 'react-places-autocomplete'
import FormControl from '@material-ui/core/FormControl'
import PropTypes from 'prop-types'

export const getCountryFromAddress = (address) => {
    if (!address) {
        return '';
    }
    try {
        const country = address.address_components.filter(component => component.types.includes('country')).map(c => c.long_name)[0];
        console.log('using country for filter ' + country);
        return country;
    } catch (error) {
        console.log(error);
        return '';
    }
}

class LocationFieldComponent extends Component {

    constructor(props) {
        super(props);
        const viewValue = this.props.value;
        this.state = {
            value: viewValue && viewValue.formatted_address
        };

        this.onSuggestionSelected = this.onSuggestionSelected.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    onChange = (e) => {

        this.setState({
            value: e.target.value
        });

        if (e.target.value === '') {
            console.log('cleared');
            this.props.onSelectionChanged('');
        }
    }

    onSuggestionSelected = (suggestion) => {

        console.log('Selected suggestion:', suggestion)
        const address = suggestion.description;
        this.setState({
            value: address
        });

        geocodeByAddress(address)
            .then(address => {
                console.log('Selected ' + JSON.stringify(address[0]));
                this.props.onSelectionChanged(address[0]);
            })
            .catch(error => console.error('Error', error))
    }

    render = () => {

        const { customStyle } = this.props;

        return (
            <FormControl className={customStyle}>
                <GooglePlaceAutocomplete
                    name="location"
                    label="Location"
                    onSuggestionSelected={this.onSuggestionSelected}
                    textFieldProps={{ onChange: (e) => this.onChange(e), value: this.state.value, placeholder: 'Search for a place'}}
                    types={['(regions)']}
                    renderTarget={() => (<div />)}
                />
            </FormControl>
        );
    }
}

LocationFieldComponent.propTypes = {
    onSelectionChanged: PropTypes.func.isRequired,
  }

export default LocationFieldComponent;

然后我按照下面的示例使用它:

代码语言:javascript
复制
<LocationFieldComponent onSelectionChanged={this.handleLocationSelected} customStyle={classes.cell}/>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51692830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档