问题描述
正如标题所述.我有一个基于react-bootstrap-typeahead
的无状态组件,以及一个基于在文档中找到formik多步向导示例.
As the title said.I have a stateless component based on react-bootstrap-typeahead
and a form wizard based on the formik multi-step wizard example found in the docs.
但是,我无法将从typeahead
组件获得的值传递给formik
.我无法访问setFieldValue
.
However, I am unable to pass the values I got from the typeahead
component into formik
. I can't access 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
中对其进行处理.任何指针或帮助,将不胜感激.谢谢
How do I inject this value into Formik
, so it can be processed onSubmit
. Any pointer or help will be appreciated.Thanks
推荐答案
Formik作者在这里...
Formik author here...
在该示例中,<Wizard />
组件呈现 ,因此FormElements
函数中的setFieldValue
实际上不在正确的范围内.如果需要访问向导页面之一中的setFieldValue
,则可以从自定义 <Field>
,使用 connect()
高阶组件和自定义组件,或直接使用 <FormikConsumer>
呈现在Formik上下文中道具.
In the example, the <Wizard />
component renders <Formik>
so the setFieldValue
in your FormElements
function is not actually in the correct scope. If you need access to setFieldValue
within one of your wizard's pages, you can get it out of a custom <Field>
, using connect()
higher order component with a custom component, or directly from Formik context using <FormikConsumer>
render prop.
我的建议是将Formik的<Field>
组件与渲染道具一起使用,如下所示:
My suggestion would be to use Formik's <Field>
component with a render prop like so:
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>
);
这篇关于如何将值从组件传递到Formik多步骤表单向导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!