我从react的formik库开始,但我不知道如何使用props handleChange和handleBlur.

根据the docs,车把可以设置为<Formik/>上的props ,然后必须手动传递到<input/>.

我试过了,但没有成功:

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>}
  />;

这种方法有什么问题?

推荐答案

您需要从Formik中删除前handleBlur个,因为模糊事件仅在字段级别有效,并在字段元素中执行以下操作:

<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

Reactjs相关问答推荐

在react中向数组状态添加值时出错

Redux向后端发送请求时出现钩子问题

try 在Dockerfile中使用AWS CLI将React构建工件上传到S3时出错

单击空白区域时,Reaction Multiple下拉组件不关闭

Reaction路由-如何在布局路由内呈现&q;/:id&q;路由

react -无法获取函数的最新参数值

根据用户 Select 的注册类型更改表单字段

StrictMode+SetInterval=双重渲染(即使使用useEffect清理)

获取类别和页面的参数

useEffect 和 ReactStrictMode

提前输入错误:选项类型上不存在属性名称

React 组件列表中的第一个计时器正在获取值 NaN

卸载 React 组件时未清除本地存储项目

Formik onChange() 字段挂钩覆盖显示值和 Select 机制

我正在通过 API(有效)从 MongoDB 传递数据.可视化但我不断收到此 TypeError: Cannot convert undefined or null to object

@react-three/postprocessing 没有匹配的从 three.module.js 导出以导入WebGLMultisampleRenderTarget

在 Formik 表单中访问子组件的值

如何从其他组件访问 useQuery refetch 方法?

网格项不缩小以适应包含的可滚动列表

如何从另一个切片中的不同切片获取状态并对其进行处理?