mui-places-autocomplete:如何订阅明文字字段事件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (138)

我正在使用mui-places-autocomplete(https://www.npmjs.com/package/mui-places-autocomplete),正如演示中所解释的。

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。但是这个库现在不起作用。

提问于
用户回答回答于

建议组件内部使用<TextField />组件。所以你应该可以用textFieldProps用于管理输入字段上的事件。

参考:https://github.com/Giners/mui-places-autocomplete/blob/master/src/MUIPlacesAutocomplete.jsx#L247

用户回答回答于
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;

然后再使用如下所示的代码:

<LocationFieldComponent onSelectionChanged={this.handleLocationSelected} customStyle={classes.cell}/>

所属标签

可能回答问题的人

  • 天使的炫翼

    17 粉丝531 提问36 回答
  • 富有想象力的人

    3 粉丝0 提问29 回答
  • o o

    4 粉丝494 提问27 回答
  • 学生

    3 粉丝476 提问27 回答

扫码关注云+社区

领取腾讯云代金券