简体   繁体   English

如何将 Formik 的 onSubmit 放在另一个组件上?

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

I have a component called WorkingHours, that renders many WeekDay components我有一个名为 WorkingHours 的组件,它呈现了许多 WeekDay 组件

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.这是我的 WeekDay 组件,它有一个 Formik 表单。 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相反,我想在“WorkingHours”组件上有一个按钮,以保存每个工作日的数据

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.您所要求的与 React 的单向数据流 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.在 React 中执行此操作的典型方法是将 state 提升一个级别,并在 WorkingHours 组件中添加 state。

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.至于formik,看起来有一个字段数组组件: https://jaredpalmer.com/formik/docs/api/fieldarray看起来就像您正在寻找将 state 提升一个级别并让您拥有您在 WorkingHours 组件中提交。

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

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