我开始使用formik库进行反应,但我无法弄清楚道具handleChange和handleBlur的使用情况。
根据the docs,handleBlur可以设置为<Formik/>
上的道具,然后必须手动向下传递到<input/>
。
我已经尝试过,但没有成功: (为了更清楚,我保留了关于handleBlur的代码)
import React from "react";
import { Formik, Field, Form } from "formik";
import { indexBy, map, compose } from "ramda";
import { withReducer } from "recompose";
const MyInput = ({ field, form, handleBlur, ...rest }) =>
<div>
<input {...field} onBlur={handleBlur} {...rest} />
{form.errors[field.name] &&
form.touched[field.name] &&
<div>
{form.errors[field.name]}
</div>}
</div>;
const indexById = indexBy(o => o.id);
const mapToEmpty = map(() => "");
const EmailsForm = ({ fieldsList }) =>
<Formik
initialValues={compose(mapToEmpty, indexById)(fieldsList)}
validate={values => {
// console.log("validate", { values });
const errors = { values };
return errors;
}}
onSubmit={values => {
console.log("onSubmit", { values });
}}
handleBlur={e => console.log("bluuuuurr", { e })}
render={({ isSubmitting, handleBlur }) =>
<Form>
<Field
component={MyInput}
name="email"
type="email"
handleBlur={handleBlur}
/>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>}
/>;
这种方法有什么问题? 如何实际使用handleBlur和handleChange?
答案 0 :(得分:14)
您需要从handleBlur
中删除第一个Formik
,因为模糊事件仅在字段级别有效,并执行类似Field元素中的以下内容:
<Field
component={MyInput}
name="email"
type="email"
handleBlur={e => {
// call the built-in handleBur
handleBlur(e)
// and do something about e
let someValue = e.currentTarget.value
...
}}
/>