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

ade*_*ola 3 reactjs react-bootstrap-typeahead formik

正如标题所说。我有一个基于文档react-bootstrap-typeaheadFormik多步骤向导示例的无状态组件和一个表单向导。

但是,我无法将从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;
Run Code Online (Sandbox Code Playgroud)

我如何将此值注入其中Formik,以便可以对其进行处理onSubmit。任何指针或帮助将不胜感激。谢谢

小智 9

Formik作者在这里...

在该示例中,该<Wizard />组件将呈现,<Formik>因此setFieldValueFormElements函数中的in 实际上不在正确的范围内。如果需要setFieldValue在向导的一个页面内访问,可以将它从custom中移出<Field>,使用connect()带有自定义组件的高阶组件,或直接使用<FormikConsumer>render prop 从Formik上下文中获取。

我的建议是将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>
);
Run Code Online (Sandbox Code Playgroud)

  • 效果很好。您可以考虑将其添加到`formik`的文档中吗?在网上搜索时,我发现了许多与此类似的未解决问题。 (5认同)