简体   繁体   中英

How can I put Formik's onSubmit on another component?

I have a component called WorkingHours, that renders many WeekDay components

const WorkingHours = () => {
  return (
    <div>
      <WeekDay day={'Monday'} />
      <WeekDay day={'Tuesday'} />
      <WeekDay day={'Wednesday'} />
      <WeekDay day={'Thursday'} />
      <WeekDay day={'Friday'} />
      <WeekDay day={'Saturday'} />
      <WeekDay day={'Sunday'} />
                        //how to add button for Formik's onSubmit here
    </div>
  )
}

This is my WeekDay component, which has a Formik Form. I don't want each weekday to have a Submit button. Rather, I'd like to have a single button at the 'WorkingHours' component, to save the data of each WeekDay

const WeekDay = ({ day }) => {
    return (
    <div>
        <Formik
           initialValues={{ begin: '', end: '' }}

    //how to transfer this button to the WorkingHours component?
    //I don't want each day to have a button to save the values
           onSubmit={(values, { setSubmitting }) => {
        }}>
          <Form>
            <Field name={} />
          </Form>  
        </Formik>
            {day}
        </div>
    )
}

What you are asking goes against React's one directional data flow model. The typical way you would do this in React would be to pull the state up a level and have the state in the WorkingHours component.

As for formik, it looks like there's a field array component: https://jaredpalmer.com/formik/docs/api/fieldarray that looks like it be what you are looking for to pull the state up a level and allow you to have your submit in the WorkingHours component.

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