我正在使用react-google-autocomplete
并且我想在按下Enter
按钮后检索第一个预测。有什么方法可以获取预测列表吗?我的想法是为Enter
按钮创建一个监听然后模拟ArrowDown
然后Enter button
但我不知道是否有办法做到这一点React
。到目前为止,我的代码如下所示:
const SearchForm = ({ onSubmit }) => {
const [location, setLocation] = useState({ lat: '', lng: '' });
const ref = useRef();
const handleKeyDown = (event) => {
if (event.keyCode === 13) {
console.log('Pressed');
}
};
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, []);
return (
<div style={{ maxWidth: '500px', width: '100%' }}>
<Form
className="bg-white rounded-pill py-1 pl-2 pr-1 mx-sm-5 d-flex align-items-center"
onSubmit={(e) => {e.preventDefault();}}
>
<div className="text-nowrap flex-grow-1">
<img
src="/svg/picto-address.svg"
alt=""
height="26"
width="26"
className="mr-2"
/>
<Autocomplete
placeholder="Where ?"
className={`${styles.unstyled} border-0 mr-3 w-100`}
onPlaceSelected={(place) => {
setLocation({ lat: place.geometry.location.lat(), lng: place.geometry.location.lng() });
onSubmit({ lat: place.geometry.location.lat(), lng: place.geometry.location.lng() });
}}
types={['address']}
componentRestrictions={{ country: 'fr' }}
ref={ref}
/>
</div>
<Button onClick={() => onSubmit(location)} size="sm" className="m-0 p-0">
<img
src="/svg/btn-search.svg"
alt=""
height="30"
width="30"
/>
</Button>
</Form>
</div>
);
};