简体   繁体   English

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

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

I'm starting out with the formik library 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 实际上应该如何使用?

You'll need to remove the first handleBlur from Formik as blur event is only valid on the field level and do something like the following in your Field element:您需要从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
        ...
    }}
/>

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

i faced the same problem using onChange method, which i think do not exist in formik props.我使用 onChange 方法遇到了同样的问题,我认为它在 formik 道具中不存在。

so i used the onSubmit method as it's available in the formik props which gives us the fields values and then passed that values to the concern function like so...所以我使用了 onSubmit 方法,因为它在 formik 道具中可用,它为我们提供了字段值,然后将该值传递给关注点 function 就像这样......

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

and there you can use, i simply updated the state and passed it to axios like so...在那里你可以使用,我只是更新了 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")
    };
  }

and its working... I hope its helps you.和它的工作......我希望它可以帮助你。

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

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