首页 > 解决方案 > 如何将 Formik 自定义组件值设置为 Formik 值

问题描述

我正在将 Formik 用于我的带有 google place 自动完成功能的表单,我想将位置自动完成呈现为 Formik 字段中的自定义组件。

表单.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 值,我对处理更改和更改功能的反应和困惑还很陌生。另外,我在这里找到了反应类组件的解决方案,但是当将这些代码转换为功能组件时,我陷入了 Onchange 和 onSlecet 函数

标签: javascriptreactjsformsformikgoogleplacesautocomplete

解决方案


基本上在更改时,您需要调用 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 状态与自动完成状态同步。

现在是选择部分。在这种情况下,您也可以采取相同的路线

 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)
  };

推荐阅读