简体   繁体   中英

React Formik insert a formik form into parent formik form

currently, I have the parent component and children component Dialog with different formik form, the brief structure which is like this

<Formik initialValues={...} onSubmit={...}>
  //some form fields here
  <Button type="submit" />
  <Button onClick={()=>{setDialogOpen(true)}}/>
  <Dialog Open={dialogOpen}>
</Formik>

<Dialog>
  <Formik initialValues={...} onSubmit={...}>
    //some form fields here
    <Button type="submit" />
  </Formik>
</Dialog>

For some reason I can't take Dialog out of the parent formik , the issue is when I click the children's submit button, the parents' formik form will also be triggered, how can I avoid this?

I would think that the submit button event is bubbling to the top formik. If you use the formik hook useFormik you can then have two separate forms and call submit on each button:

import { useFormik } from 'formik';
const [parentForm] = useFormik();
const [dialogForm] = useFormik();

<Formik initialValues={...} onSubmit={...} form={parentForm}>
  //some form fields here
  <Button onClick={() => parentForm.submit()} />
  <Button onClick={()=>{setDialogOpen(true)}}/>
  <Dialog Open={dialogOpen}>
</Formik>

<Dialog>
  <Formik initialValues={...} onSubmit={...} form={dialogForm}>
    //some form fields here
    <Button onClick={() => dialogForm.submit()} />
  </Formik>
</Dialog>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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