我在google place自动完成的表单中使用Formik,我想将places自动完成呈现为Formik字段中的一个自定义组件。
form.js
<Formik initialValues={location:""}>
<Field name="location" component={PlacesAutoComplete} placeholder="enter your location"/>
{...rest of form}
</Formik>自动完成组件
import PlacesAutocomplete , {
geocodeByAddress,
geocodeByPlaceId
} from "react-google-places-autocomplete";
export const PlacesAutoComplete = ({
field: { name, ...field }, // { name, value, onChange, onBlur }
form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
classes,
label,
...props
}: any) => {
const [fieldName, setFildName] = React.useState(field.name);
const [address, setAddress] = React.useState(props.value || "");
const error = errors[name];
// const touch = touched[name];
const handleSelect = () => {
// set this value to formik value
};
const handleChange = () => {
// set this value to formik value
};
const handleError = () => {
props.form.setFieldError(fieldName, error);
};
return (
<PlacesAutocomplete
value={address}
onChange={handleChange}
onSelect={handleSelect}
onError={handleError}
name={name}
placeholder={props.placeholder}
id={name}
{...props}
apiKey="Api key here"
>
{({
getInputProps,
suggestions,
getSuggestionItemProps,
loading
}: any) => (
<div>
<input
{...getInputProps({
placeholder: "Search Places ...",
className: "location-search-input form-control"
})}
/>
<div className="autocomplete-dropdown-container">
{loading && <div>Loading...</div>}
{suggestions.map((suggestion: any) => {
const className = suggestion.active
? "suggestion-item--active"
: "suggestion-item";
// inline style for demonstration purpose
const style = suggestion.active
? { backgroundColor: "#fafafa", cursor: "pointer" }
: { backgroundColor: "#ffffff", cursor: "pointer" };
return (
<div
{...getSuggestionItemProps(suggestion, {
className,
style
})}
>
<span>{suggestion.description}</span>
</div>
);
})}
</div>
</div>
)}
</PlacesAutocomplete>
);
};我如何将位置自动补全值设置为formik值,我对处理更改和更改函数感到非常陌生和困惑。此外,我在react类组件here中找到了一个解决方案,但在将这些代码转换为功能组件时,我陷入了Onchange和onSlecet函数
发布于 2021-08-31 19:59:27
最好不要写函数组件,因为如果你在写,你会被测试用例卡住。
即使你输入任何东西,onChange的值也会存储在OnChange中。Abe onSelect是当您选择任何内容时
发布于 2021-08-31 20:39:10
基本上,在发生更改时,您需要调用formik的字段onChange函数。因此,如果您在handleChange上遇到事件,只需执行以下操作
const handleChange = (event) => {
// set this value to formik value
field.onChange(event.target.value)
};或者,如果您在handleChange中获得值,则执行以下操作
const handleChange = (value) => {
// set this value to formik value
field.onChange(value)
};这将使您的formik状态与自动完成状态同步。
现在是select的部分。在这种情况下,您也可以采用相同的路线
const handleSelect = (value) => {
// set this value to formik value
field.onChange(value)
};或者您可以使用form的setField函数来更新值
const handleSelect = (value) => {
// set this value to formik value
form.setField('location',value)
};https://stackoverflow.com/questions/69004636
复制相似问题