React Formik:如何使用自定义onChange和onBlur

Nic*_*all 27 javascript forms reactjs

我开始使用formik库进行反应,我无法弄清楚道具handleChange和handleBlur的用法.

根据文档,handleBlur可以设置为a上的prop <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>}
  />;
Run Code Online (Sandbox Code Playgroud)

这种方法有什么问题?handleBlur和handleChange实际上应该如何使用?

Ric*_*hen 26

您需要删除第一个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
        ...
    }}
/>
Run Code Online (Sandbox Code Playgroud)

请参阅https://github.com/jaredpalmer/formik/issues/157

  • 只要您不需要操纵该值就可以。就我而言,我想在自定义模糊处理程序中重新格式化字段的值,这会触发验证问题,因为“setFieldValue()”不是异步的。请参阅 https://github.com/jaredpalmer/formik/issues/529 (2认同)
  • 我认为这是一个单独的 Formik 问题,在没有一些解决方法的情况下,在同一字段上执行“setFieldValue()”后,您无法立即获取更新的字段值。我是那次讨论的参与者之一。 (2认同)