如何将Formik自定义组件值设置为Formik值



我使用Formik为我的表单与谷歌的地方自动完成,我想渲染的地方自动完成作为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类组件中找到了一个解决方案,但是当将这些代码转换为功能组件时,我被困在Onchange和onecet函数中

最好不要写功能组件,因为如果你在写测试用例,你会被卡住。

OnChange是即使你输入任何东西,值被存储在OnChange。Abe onSelect是当你选择任何东西

基本上在更改时您需要调用formik的字段onChange函数。因此,如果你在handleChange上得到一个事件,只需执行这个

const handleChange = (event) => {
// set this value to formik value
field.onChange(event.target.value)
};

或者如果你在handleChange中得到value那么执行

const handleChange = (value) => {
// set this value to formik value
field.onChange(value)
};

这将同步你的表单状态和自动完成状态。

现在是select部分。在这种情况下,你也可以走同样的路线

const handleSelect = (value) => {
// set this value to formik value
field.onChange(value)
};

或者您可以使用表单的setField函数来更新值

const handleSelect = (value) => {
// set this value to formik value
form.setField('location',value)
};

最新更新