简体   繁体   English

在卸载时提交 Formik 表单

[英]Submitting a Formik Form on Unmount

Is it possible to submit a Formik Form without having a submit button?是否可以在没有提交按钮的情况下提交 Formik 表单? For example submitting the Form when the component unmounts so the user doesn't need to click a button to save.例如,当组件卸载时提交表单,这样用户就不需要单击按钮来保存。 Think of something like that:想想这样的事情:

import React from "react";
import { Formik, Form, Field } from "formik";

const Example = () => {
  useEffect(() => {
    return () => {
      //trigger Submit or send Request with Form Values from here
    };
  }, []);

  return (
    <Formik
      initialValues={{
        firstName: "",
        lastName: "",
      }}
      onSubmit={(values, { setSubmitting }) => {
        //send Request
      }}
    >
      {() => (
        <Form>
          <Field name="firstName" />
          <Field name="lastName" />
        </Form>
      )}
    </Formik>
  );
};

export default Example;

You can create a functional component that auto-submits.您可以创建一个自动提交的功能组件。 By having it render inside the component, you have reference to the context of the form.通过让它在组件内呈现,您可以引用表单的上下文。 You can use:您可以使用:

import { useFormikContext } from 'formik';
 
 function AutoSubmitToken() {
   // Grab values and submitForm from context
   const { values, submitForm } = useFormikContext();

   React.useEffect(() => {
     return submitForm;
   }, [submitForm]);
   return null;
 };

You can use it under the component as such您可以在组件下使用它

<Form>
   <Field name="token" type="tel" />
   <AutoSubmitToken />
</Form>

You can read all about it here你可以在这里阅读所有相关信息

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

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