问题描述
我开始使用库进行反应,我无法弄明白使用道具handleChange和handleBlur。
I'm starting out with the formik library for react, and I can't figure out the usage of the props handleChange and handleBlur.
根据,handleBlur可以设置为< Formik />
上的道具,然后必须手动传递下到< input />
。
According to the docs, handleBlur can be set as a prop on a <Formik/>
, and then has to be passed manually down to the <input/>
.
我试过了,没有成功:
(为了更清楚,我保留了关于handleBlur的代码)
I've tried that, with no success :(I'm keeping the code about handleBlur for more clarity)
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?
What is wrong with this approach ?How are handleBlur and handleChange actually supposed to be used ?
推荐答案
你需要删除第一个 handleBlur
来自 Formik
因为模糊事件仅在字段级别有效,并且在您的Field元素中执行以下操作:
You'll need to remove the first handleBlur
from Formik
as blur event is only valid on the field level and do something like the followings in your Field element:
<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
...
}}
/>
参见
这篇关于React Formik:如何使用自定义onChange和onBlur的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!