首页 > 解决方案 > 第一个 React-Bootstrap 单选按钮单击未触发 Formik 表单中的“触摸”

问题描述

沙盒:https ://codesandbox.io/s/nervous-bogdan-rdf1q

我在 Formik 表单中有一个 React-Bootstrap 广播组。如果您单击,Option 2您会注意到我立即在该字段上正确收到了验证错误,但我没有立即触及该字段,我应该这样做。相反,我必须再次Option 2单击单选按钮才能将其放入 Formik触摸数组中。因此,如果我从该单选按钮开始,则在我的第一次单击时触摸不会注册,尽管错误是(正确)。触摸正在注册后续点击。

        <Form.Group>
          <Form.Control type="radio"
                        id="option1"
                        name="group"
                        value="Y"
                        onChange={handleChange}
                        onBlur={handleBlur}
          />
          <Form.Label htmlFor="option1">Option 1 </Form.Label>
        </Form.Group>
        <Form.Group>
          <Form.Control type="radio"
                        id="option2"
                        name="group"
                        value="N"
                        onChange={handleChange}
                        onBlur={handleBlur}
          />
          <Form.Label htmlFor="option2">Option 2 </Form.Label>
        </Form.Group>

验证:

<Formik
  initialValues={{
  }}
  validationSchema={Yup.object().shape({
    group: Yup.string().nullable().required('Required')
                                  .matches(/^Y$/,'Option 1 must be selected')
  })}
>

标签: reactjsreact-bootstrapformik

解决方案


我发现了问题。单选按钮在选择后保持焦点,因此第一次更新.touched只会在您单击其他位置以在第一次单击后模糊控件时发生。

这可以通过做来解决

  onChange={e => {
    // Note: Since radio buttons remain focused after selection,
    // we need to manually blur them to immediately update .touched
    // (including the first click)                                                                  
    e.currentTarget.blur();
    handleChange(e);
  }} 

推荐阅读