如何从一个组件值传递到Formik多步骤表单向导?

问题描述 投票:2回答:1

正如标题说。我有一个基于react-bootstrap-typeahead和基于文档中发现的formik multi-step wizard example表单向导无状态组件。

但是,我无法通过我从typeahead组件到formik得到的值。我无法访问setFieldValue

    const FormElements = setFieldValue => (
        <Wizard
          initialValues={FORM_VALUES}
          onSubmit={(values, actions) => {
            sleep(300).then(() => {
              window.alert(JSON.stringify(values, null, 2));
              actions.setSubmitting(false);
            });
          }}
        >
          <Wizard.Page>
            <GoogleMapsPlaceLookup
              value={location => {
                console.log("I got the value correctly from my child: ", location);
              }}
            />
          </Wizard.Page>
        </Wizard>
    );

    export default FormElements;

如何注入该数值到Formik,因此它可以处理onSubmit。任何指针或帮助将不胜感激。谢谢

reactjs formik react-bootstrap-typeahead
1个回答
8
投票

Formik笔者在这里...

In the example, the <Wizard /> component renders <Formik>所以在你的setFieldValue功能FormElements实际上不是在正确的范围。如果您需要访问你的向导页之一内setFieldValue,您可以使用<Field>渲染道具从Formik背景下把它弄出来一个自定义connect(),用<FormikConsumer>高阶组件与自定义组件,或直接。

我的建议是使用Formik的<Field>成分,象这样渲染道具:

const FormElements = () => (
  <Wizard
    initialValues={FORM_VALUES}
    onSubmit={(values, actions) => {
      sleep(300).then(() => {
        window.alert(JSON.stringify(values, null, 2));
        actions.setSubmitting(false);
      });
    }}
  >
    <Wizard.Page>
      <Field name="location">
        {({ field, form }) => (
          <GoogleMapsPlaceLookup
            value={field.value /* make sure to somehow connect Formik's stored value state to the input */}
            onChange={location => {
              console.log('I got the value correctly from my child: ', location);               
              // Manually set Formik values.location and trigger validation
              form.setFieldValue('location', location);
            }}
          />
        )}
      </Field>
    </Wizard.Page>
  </Wizard>
);
© www.soinside.com 2019 - 2024. All rights reserved.