本文介绍了如何使用formik react js在handlesubmit函数中接收选择值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用formik插件插件链接在reactjs中开发表单.当我提交表单时,我正在获取文本字段值,但下拉列表值将为空...

i am developing a form in reactjs using formik plugin plugin link. when i submit form i am getting text fields values but dropdown values are coming empty...

这是我的下拉选择

<div className="form-group">                  
                <Field component="select" id="category" name="category" value={this.state.value} className={"form-control"} onChange={ this.handleChange }>
                   <option value="lokaler">Lokaler</option>
                   <option value="jobb">Jobb</option>
                   <option value="saker-ting">Saker & ting</option>
                   <option value="evenemang">Evenemang</option>
                </Field>
                  </div>

处理提交功能

export default withFormik({
  enableReinitialize: true,
  mapPropsToValues({ category }) {
    return {      
      category: category || ''
    }
  },
    handleSubmit(values, { setStatus, setErrors }){
      console.log("data is this: "); 
      console.log(values); //here i am getting all form fields values except select value returning empty value
      console.log("category: "+values.category);// here i always get empty value but not getting selected value

      }

我正在获取句柄提交功能中的所有文本字段值,但是我无法获取下拉选择值....请告诉我如何在句柄提交功能中获取下拉选择值?

i am getting all text fields values in handle submit function but i am not able to get dropdown selected value....kindly tell me how to get dropdown select value in handle submit function ?

推荐答案

昨天我也遇到了这个问题.我的问题是提交包含蚂蚁设计下拉列表的表单.经过数小时的努力,我终于使它工作了:

I also faced this problem yesterday. My problem was to submit form that contains ant design dropdown. I finally make it work after hours of:

  • revisiting the Formik Docs
  • watch Andrew Mead's video Better React Form with Formik again.
  • also viewing Jared Palmer's Working with 3rd-party inputs #1: react-select

医生说,您需要将 onChange onBlur 事件分别设置为 setFieldValue setFieldTouched 道具,例如3rd -party输入示例:

The doc said you need to set onChange, onBlur events to setFieldValue, setFieldTouched props respectively like 3rd-party input example:

<MySelect
    value={values.topics}
    onChange={setFieldValue}
    onBlur={setFieldTouched}
    error={errors.topics}
    touched={touched.topics}
/>

对于我的问题,我需要更改一下:

So to my problem, I need to change a bit:

<Select
  {...field}
  onChange={(value) => setFieldValue('fruitName', value)}
  onBlur={()=> setFieldTouched('fruitName', true)}
  value={values.fruitName}
  ...
>
...
</Select>

希望这会有所帮助.

这是我的 CodeSandbox

这篇关于如何使用formik react js在handlesubmit函数中接收选择值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 04:35