简体   繁体   English

如何访问 formik helpers Insider formik wrapper 组件来设置特定字段的字段值

[英]How can I access formik helpers insider formik wrapper component to set field value of a particular field

I am following a tutorial to create a multistep form with formik by creating a formik wrapper component.我正在按照教程通过创建 formik 包装器组件来使用 formik 创建多步表单。 So far it works for normal field elements.到目前为止,它适用于普通字段元素。 But I have certain scenarios where I wish to use setFieldValue to set some values of custom component, the formik helpers are inaccessible to the child elements of the wrapper.但是在某些情况下,我希望使用 setFieldValue 来设置自定义组件的某些值,formik 助手无法访问包装器的子元素。 Can someone help me on how can I use formik helpers to set values of a child element of a wrapper.有人可以帮助我如何使用 formik 助手来设置包装器的子元素的值。

Here is the example link which I am following.这是我正在关注的示例链接

This is what I am trying to achieve -这就是我想要实现的 -

 <FormikStepper
  initialValues={{...values}}
  onSubmit={someFunction}
  onReset={() => {}}> 
<FormikStep label='Step 1' validationSchema={Step1ValidationSchema}>
<label>Some Label</label>
 <input
  name='image'
  type='file'
  className=''
  onChange={(e) => {setFieldValue("image", e.target.files[0]);}}
  />
<ErrorMessage name='image'/>
</FormikStep>

How can I be able to access it for setting the value of a child.我怎样才能访问它来设置孩子的价值。 I tried creating a context but I am confused on where to initialize the context.ie As to where and how should I initialize the context for this particular scenario.我尝试创建一个上下文,但我对在哪里初始化上下文感到困惑。即我应该在哪里以及如何为这个特定场景初始化上下文。

Better way is to extract input into separate component and then you can use setFieldValue inside that component:更好的方法是将input提取到单独的组件中,然后您可以在该组件中使用setFieldValue

const ImageInput = (props) = {
 const [setFieldValue] = useFormikContext()
 ...
}

The reason why it works is that all your components wrapper by formik Form .它起作用的原因是您的所有组件都由 formik Form包装。

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

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