javascript - react 福米克 : how to use custom onChange and onBlur

标签 javascript forms reactjs

我从 formik 开始库用于 react ,我无法弄清楚 Prop handleChange和handleBlur的用法。

根据the docs ,handleBlur 可以设置为<Formik/> 上的 Prop 。 ,然后必须手动向下传递到 <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?

最佳答案

您需要从 Formik 中删除第一个 handleBlur,因为模糊事件仅在字段级别有效,并在 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
        ...
    }}
/>

参见https://github.com/jaredpalmer/formik/issues/157

关于javascript - react 福米克 : how to use custom onChange and onBlur,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48466920/

相关文章:

javascript - 我想要两个 mysql 表与 group_concat 连接导致 json 数组

node.js - 如何使用 ExpressJS 一次 API 调用下载多个文件

node.js - 如何在 React 应用程序中自定义 Bootstrap 变量?

javascript - 根据 API 响应递归呈现项目列表

javascript - 将焦点设置为输入元素 Angular js

javascript - jQGrid,如何使列在添加对话框中可编辑但在(内联)编辑期间不可编辑

javascript - `Vue3 - Vite` 项目别名 src 到 @ 不工作

javascript - CRM 2011 - 单击关联 View 或子网格中自己的记录链接时出现奇怪的行为形式

Javascript根据另一个下拉框值更改下拉框选项

html - 在电子邮件中嵌入 HTML 表单