In formik, shorthand input field is not working

痞子三分冷 提交于 2019-12-24 21:42:09

问题


In Formik, I try to use {...formik.getFieldProps('email')} on my input field instead of using value, onChange, and onBlur. But it's not working.

This works :

<input id="email" name="email" type="text" value={formik.values.email} onChange={formik.handleChange} onBlur={formik.handleBlur} />

But this doesn't :

<input id="email" type="text" {...formik.getFieldProps("email")} />

Code is here : https://codesandbox.io/s/formik-pb-with-getfieldprops-83tze?fontsize=14

Any ideas ? Thanks !


回答1:


As MiDas said, what you are doing should work if you are on latest version.

I'll mention an even more concise alternative: the Field component.

Field component handles the field property propagation for you.

Simple example:

<Field name="email" type="text" />

Notice that you don't need to do {...formik.getFieldProps("email")}, or any other "boilerplate".


Related to Field is useField, which can be used to make custom form components just as easy to use - no "boilerplate" needed.

A custom component:

function TextInputWithLabel({ label, ...props }) {
  // useField() returns [formik.getFieldProps(), formik.getFieldMeta()]
  // which we can spread on <input> and also replace ErrorMessage entirely.
  const [field, meta] = useField(props);
  return (
    <>
      <label
        htmlFor={props.id || props.name}
        css={{ backgroundColor: props.backgroundColor }}
      >
        {label}
      </label>
      <input className="text-input" {...field} type="text" {...props} />
      {meta.touched && meta.error ? (
        <div className="error">{meta.error}</div>
      ) : null}
    </>
  );
}

Usage:

<TextInputWithLabel name="input1" label="Random comment" />

As seen in code from codesandbox.



来源:https://stackoverflow.com/questions/58675463/in-formik-shorthand-input-field-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!