在Formik中,我尝试在输入字段上使用{... formik.getFieldProps('email')} 而不是使用value,onChange和onBlur。但这不起作用。
这有效:
<input id="email" name="email" type="text" value={formik.values.email} onChange={formik.handleChange} onBlur={formik.handleBlur} />
但这不是:
<input id="email" type="text" {...formik.getFieldProps("email")} />
代码在这里:https://codesandbox.io/s/formik-pb-with-getfieldprops-83tze?fontsize=14
有什么想法吗? 谢谢!
答案 0 :(得分:1)
如MiDas所说,如果您使用的是最新版本,您正在做的事情应该会起作用。
我将提到一个更简洁的选择:Field组件。
字段组件为您处理字段属性的传播。
简单的例子:
<Field name="email" type="text" />
请注意,您无需执行{...formik.getFieldProps("email")}
或任何其他“样板”。
与Field
相关的是useField
,它可以用来制作自定义表单组件,就像使用起来一样容易-不需要“样板”。
自定义组件:
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}
</>
);
}
用法:
<TextInputWithLabel name="input1" label="Random comment" />