reactjs - 为自定义输入字段实现一个清除按钮,以使用反应挂钩表单触发所需的错误
问题描述
期待
当我们用十字按钮清除输入字段时,React Hook 表单应该显示错误消息
问题
- 使用十字按钮清除值后未显示所需的错误消息。
- 使用十字按钮清除值后,提交按钮未被禁用。
自定义输入字段的代码
import React, { useRef } from 'react';
export default function MyInput(props) {
const inputRef = useRef();
const clear = () => {
if (inputRef.current) {
inputRef.current.value = '';
}
}
return (
<>
<input ref={inputRef} {...props} />
{/* I want to trigger the required error of react hook form on clear*/}
<button onClick={clear} style={{
marginLeft: '-1.2rem',
cursor: 'pointer'
}}>x</button>
</>
);
}
表格中的用法
<Controller
name="firstName"
control={control}
rules={{
required: {
value: true,
message: 'You must enter your first name'
}
}}
render={({ field: { ref, ...rest } }) => <CustomInput {...rest} />}
/>
不确定是否useRef
是正确的方法,但我想使用一个不受控制的输入,我想用一个清除按钮自定义
链接到 Stackblitz -带有清除按钮的自定义输入
解决方案
让表单知道单击清除按钮时更改的setValue
一种方法是从useForm
钩子中调用该方法以手动注册更改。
因此,我可以将 setValue 作为道具传递给我的子组件,即自定义输入,并在输入字段的清除按钮的单击事件上设置新值
const clear = () => {
setValue(name, '', {
shouldValidate: true,
shouldDirty: true
});
}
此useRef
用例也不需要。
链接到更新的 Stackblitz -带有清除按钮的自定义输入
推荐阅读
- python - 在 Google Colab 上运行 .EXE 或 Perl 文件
- r - 减去组内的值
- python - 如何在 Plotly 动画的单帧中显示不同颜色的 3D 网格图?
- python - 如何读取 2 列 .txt 文件并将其存储在 python 中的 x 和 y 变量中
- javascript - 从 URL 字符串中删除信息
- r - tf-hub 和食谱 / tidymodels
- git - 有没有办法在更改后查看原始 Git 提交时间?
- datetime - 处理时区差异
- java - Java 将文件读取到多个类会引发错误
- javascript - 如何使用音频自动播放 MediaStreams 或视频元素?