Javascript React Formik:如何使用自定义 onChange 和 onBlur
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48466920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Formik : how to use custom onChange and onBlur
提问by Nicolas Marshall
I'm starting out with the formiklibrary for react, and I can't figure out the usage of the props handleChange and handleBlur.
我开始使用formik库进行 react,我无法弄清楚道具 handleChange 和 handleBlur 的用法。
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 设置为 上的道具<Formik/>,然后必须手动向下传递到<input/>.
I've tried that, with no success : (I'm keeping the code about handleBlur for more clarity)
我已经尝试过了,但没有成功:(为了更清晰,我保留了有关 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>}
/>;
What is wrong with this approach ? How are handleBlur and handleChange actually supposed to be used ?
这种方法有什么问题?实际上应该如何使用 handleBlur 和 handleChange ?
采纳答案by Rico Chen
You'll need to remove the first handleBlurfrom Formikas blur event is only valid on the field level and do something like the following in your Field element:
您需要删除第一个handleBlurfromFormik因为 blur 事件仅在字段级别有效,并在 Field 元素中执行以下操作:
<Field
component={MyInput}
name="email"
type="email"
onBlur={e => {
// call the built-in handleBur
handleBlur(e)
// and do something about e
let someValue = e.currentTarget.value
...
}}
/>

