因此,基本上,我使用的是react-places-autocomplete,并且当用户点击其中一个地址建议时,我尝试调用click函数。当我使用鼠标时,它可以工作,但当我使用键盘时,它不工作。请检查我的代码
我试过onSelect onKeyPressed,它们不起作用。
import React, { useState, useEffect } from "react";
import "./Location.css";
import PlacesAutocomplete, { geocodeByAddress,getLatLng } from "react-places-autocomplete";
import { Paper, TextField } from "@material-ui/core";
function AddLocation(props) {
//here is the function
const handleClick = () => {
console.log("the function is called ");
};
return (
<Paper elevation="5">
<div style={{ padding: 10 }}>
<PlacesAutocomplete
value={address}
onChange={handleChange}
onClick={handleChange}
>
{({ getInputProps, suggestions, getSuggestionItemProps, load }) => (
<>
<TextField
id="outlined-name"
label="Address"
error={errors.address}
value={address}
helperText={errors.address}
name="name"
style={{ width: "100%" }}
variant="outlined"
{...getInputProps({
placeholder: "Search Places ...",
className: "location-search-input"
})}
/>
<div className="autocomplete-dropdown-container">
{load && <div>Loading...</div>}
{suggestions.map(suggestion => {
const className = suggestion.active
? "suggestion-item--active"
: "suggestion-item";
const style = suggestion.active
? {
backgroundColor: "#fafafa",
cursor: "pointer"
}
: {
backgroundColor: "#ffffff",
cursor: "pointer"
};
return (
<div
{...getSuggestionItemProps(suggestion, {
className,
style
})}
>
{/* /////////////////here is my onClick////////////// */}
<div onClick={handleClick}>
<span>{suggestion.description}</span>
</div>
{/* ///////////////////////////////////////////////////////// */}
</div>
);
})}
</div>
</>
)}
</PlacesAutocomplete>
</div>
</Paper>
);
}
export default AddLocation;
我希望当我单击其中一个建议时,鼠标单击和键盘单击会调用我的函数
发布于 2019-08-09 12:00:48
在react-places-autocomplete
repo上,有人遇到了和你一样的问题:here。解决方案:
const inputProps = getInputProps({ placeholder: locationPlaceholder });
const onKeyDown = (event) => {
const suggestionsOpen = !!suggestions.length; // find out if suggestions are active or not
inputProps.onKeyDown(event); // do the normal onKeyDown callback
if(!suggestionsOpen && event.keyCode === 13){ // if this is enter key, submit form
this.submitForm();
}
}
<input type="text" {...inputProps} onKeyDown={onKeyDown} />
https://stackoverflow.com/questions/57414278
复制相似问题