我只想在建议中输入城市和相关国家/地区,同时在react-places-autocomplete的搜索字段中输入一些内容。我尝试使用 searchOptions 道具,并在其中放置了 {{type:['(city)','(country)']}} ,该方法不起作用。为了使事情像这样工作,我应该在那里使用? 有人遇到同样的问题吗? 有帮助吗?
以下是我的代码:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import PlacesAutocomplete, { geocodeByAddress, geocodeByPlaceId, getLatLng } from 'react-places-autocomplete';
const isObject = val => {
return typeof val === 'object' && val !== null;
};
const classnames = (...args) => {
const classes = [];
args.forEach(arg => {
if (typeof arg === 'string') {
classes.push(arg);
} else if (isObject(arg)) {
Object.keys(arg).forEach(key => {
if (arg[key]) {
classes.push(key);
}
});
} else {
throw new Error(
'`classnames` only accepts string or object as arguments'
);
}
});
return classes.join(' ');
};
class App extends Component {
constructor() {
super();
this.state = {
name: "React",
postAddress: "",
post_address_obj: {},
errorMessage: "",
latitude: null,
longitude: null,
isGeocoding: false
};
}
handlePostAddressChange = address => {
// console.log(address);
this.setState({
postAddress: address,
latitude: null,
longitude: null,
errorMessage: ""
});
};
render() {
return (
<div>
<div
id="post_elements_5"
className="div-capsule-margin location_margin"
>
<PlacesAutocomplete
value={this.state.postAddress}
onChange={this.handlePostAddressChange}
>
{({ getInputProps, suggestions, getSuggestionItemProps }) => {
return (
<div className="Demo__search-bar-container">
<div className="Demo__search-input-container">
<input
{...getInputProps({
placeholder: "Tag the location",
className: "Demo__search-input"
})}
/>
{this.state.postAddress.length > 0 && (
<button
className="Demo__clear-button"
onClick={this.handleCloseClick}
>
x
</button>
)}
</div>
{suggestions.length > 0 && (
<div className="Demo__autocomplete-container">
{suggestions.map(suggestion => {
const className = classnames("Demo__suggestion-item", {
"Demo__suggestion-item--active": suggestion.active
});
return (
/* eslint-disable react/jsx-key */
<div
{...getSuggestionItemProps(suggestion, {
className
})}
>
<strong>
{suggestion.formattedSuggestion.mainText}
</strong>{" "}
<small>
{suggestion.formattedSuggestion.secondaryText}
</small>
</div>
);
/* eslint-enable react/jsx-key */
})}
<div className="Demo__dropdown-footer">
<div>
<img
src="http://files.hostgator.co.in/hostgator254362/image/powered-by-google.png"
className="Demo__dropdown-footer-image"
/>
</div>
</div>
</div>
)}
</div>
);
}}
</PlacesAutocomplete>
</div>
</div>
);
}
}
render(<App />, document.getElementById('root'));
答案 0 :(得分:-1)
searchOptions
将用于AutocompletionRequest,它使您可以指定types
of the response。
<PlacesAutocomplete
value={this.state.postAddress}
onChange={this.handlePostAddressChange}
searchOptions={{ types: ['locality', 'country'] }}
>