【问题标题】:First React-Bootstrap Radio Button Click is not triggering "touched" in Formik Form第一个 React-Bootstrap 单选按钮单击未触发 Formik 表单中的“触摸”
【发布时间】:2021-05-24 18:20:39
【问题描述】:

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

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

        <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')
  })}
>

【问题讨论】:

    标签: reactjs react-bootstrap formik


    【解决方案1】:

    我发现了问题。单选按钮在选择后保持焦点,因此.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);
      }} 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多