繁体   English   中英

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

[英]React Formik : how to use custom onChange and onBlur

我开始使用formik库进行react,但我无法弄清楚道具handleChange 和handleBlur 的用法。

根据文档,handleBlur 可以设置为<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>}
  />;

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

您需要从Formik删除第一个handleBlur ,因为 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
        ...
    }}
/>

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

我使用 onChange 方法遇到了同样的问题,我认为它在 formik 道具中不存在。

所以我使用了 onSubmit 方法,因为它在 formik 道具中可用,它为我们提供了字段值,然后将该值传递给关注点 function 就像这样......

<Formik
          initialValues={initialValues}
          validationSchema={signInSchema}
          onSubmit={(values) => {
            registerWithApp(values);
            console.log(values);
          }}
        >

在那里你可以使用,我只是更新了 state 并将其传递给 axios 就像这样......

    const [user, setUser] = useState({
    name: "",
    email: "",
    password: ""
  });

  const registerWithApp = (data) => {
    const { name, email, password } = data;
    setUser({
      name:name,
      email:email,
      password:password
    })
   
    if (name && email && password) {
      axios.post("http://localhost:5000/signup", user)
        .then(res => console.log(res.data))
    }
    else {
      alert("invalid input")
    };
  }

和它的工作......我希望它可以帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM