reactjs - 第一个 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')
})}
>
解决方案
我发现了问题。单选按钮在选择后保持焦点,因此第一次更新.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);
}}
推荐阅读
- python - 在 ImageDataGenerator 中将 int 标签转换为 one_hot 编码(分类)
- reactjs - 如何使用 react-router 链接访问 React 打字稿中的 props.location?
- can-bus - 行驶记录仪远程身份验证
- ldap - 如何查询 OpenLDAP 的 posixGroup 成员资格?
- azure-log-analytics - 从查询中获取输出并在后续 KQL 查询中使用
- api - 计算推文
- flutter - 无法访问 webview 输入文件相机
- gis - 具有连接字段的 IIF 语句 - Arcade/Python
- php - PHP:从每个循环访问数组索引以在外部数组中使用时出现未定义的索引错误?
- wordpress - Wordpress SASS 编译器 - 没有 mixin 命名媒体