为自定义输入字段实现一个清除按钮,以使用反应挂钩表单触发所需的错误
Implement a clear button for a custom input field to trigger required error with react hook form
预期
当我们使用十字按钮清除输入字段时,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
是否正确,但我想使用不受控制的输入,我想使用清除按钮进行自定义
Link 到 Stackblitz - Custom Input with clear Button
让表单知道单击清除按钮时更改的一种方法是从 useForm
挂钩调用 setValue
方法以手动注册更改。
因此,我可以将 setValue 作为道具传递给我的子组件,即自定义输入
并在输入字段的清除按钮的点击事件上设置新值
const clear = () => {
setValue(name, '', {
shouldValidate: true,
shouldDirty: true
});
}
此外,此用例不需要 useRef
。
Link 到更新的 Stackblitz - Custom Input with clear Button
预期
当我们使用十字按钮清除输入字段时,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
是否正确,但我想使用不受控制的输入,我想使用清除按钮进行自定义
Link 到 Stackblitz - Custom Input with clear Button
让表单知道单击清除按钮时更改的一种方法是从 useForm
挂钩调用 setValue
方法以手动注册更改。
因此,我可以将 setValue 作为道具传递给我的子组件,即自定义输入 并在输入字段的清除按钮的点击事件上设置新值
const clear = () => {
setValue(name, '', {
shouldValidate: true,
shouldDirty: true
});
}
此外,此用例不需要 useRef
。
Link 到更新的 Stackblitz - Custom Input with clear Button