简体   繁体   English

使用 formik 如何在选择 TypeAhead 字段时将值添加到 formik 值

[英]Using formik how to add values to formik values when TypeAhead field is selected

I'm using formik for my form with a TypeAhead field that allow the user to select array of objects.我将 formik 用于带有 TypeAhead 字段的表单,该字段允许用户访问 select 对象数组。 I want to update Formik values with the array of objects when selected.我想在选择时用对象数组更新 Formik 值。 How do I update formik values when the value has been selected?选择值后如何更新 formik 值? I have tried setFieldValue, but how can it be done in this manner?我已经尝试过 setFieldValue,但是如何以这种方式完成呢?

 <Formik
  initialValues={{
    driverList: [
      {
        id:'',
        firstName: '',
        lastName: '',
        smsPhone: '',
        email: ''
      }
    ],
  }}
  validationSchema={Yup.object({
    activateAccount: Yup.boolean()
      .required('Required')
      .oneOf([true], 'Account must be activated.'),
  })}
  onSubmit={values => {
    alert(JSON.stringify(values, null, 4));
    console.log(values)
  }}
  >
{({handleSubmit, setFieldValue, values}) => (
  <div>
    <Card className="callSupportCard">
      <Card.Body>
        <Card.Title className="callSupportTitle">
          Account Activation
        </Card.Title>
        <Card.Subtitle className="callSupportCheckBox">
          The customer has started to setup up his/her account but could not finish.
        </Card.Subtitle >
        <p className="callQuestion">{" "}<b>Step 1:{" "}</b> Ask for their first and last name.</p>
        <Form onSubmit={handleSubmit}>
          <Typeahead className="driverInput" id="driversInfo" 
                                        labelKey={(option) => `${option.firstName} ${option.lastName}, ${option.smsPhone}, ${option.email}`}
                                        onChange={setSelected} 
                                        options={options} 
                                        selected={selected}
                                        placeholder="Choose an driver..." 
              />

Solution was:解决方案是:

 <Typeahead 
  labelKey={(option) => `${option.firstName} ${option.lastName},  ${option.phone}, ${option.email}`}
           onChange={(selected) => {
                      if(selected.length > 0)
                      {setFieldValue('firstName', selected[0].firstName);
                       setFieldValue('lastName', selected[0].lastName);
                       setFieldValue('smsPhone', selected[0].phone);
                       setFieldValue('email', selected[0].email);
                       setFieldValue('suspended', selected[0].suspended);
                      }}}
            options={options} 
            placeholder="Choose an person..." 
            />

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

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