Reactjs 反应钩形罐';单击按钮重置输入,看不到更改值
带有输入和重置输入按钮的组件Reactjs 反应钩形罐';单击按钮重置输入,看不到更改值,reactjs,react-hook-form,Reactjs,React Hook Form,带有输入和重置输入按钮的组件TexInputComponent: <input type={type} name={name} ref={register} /> <button type="button" onClick={clearInput}> Reset input </button> const clearInput = () => { document.querySelecto
TexInputComponent
:
<input
type={type}
name={name}
ref={register}
/>
<button
type="button"
onClick={clearInput}>
Reset input
</button>
const clearInput = () => {
document.querySelector(`#${name}`).value = null;
};
现在,当我单击表单react hook表单上的提交时,返回我的错误,例如“需要标题!”。当我在TexInputComponent
中写东西时,就会出现错误。
问题是当我写文本并单击按钮重置输入时。执行clearInput
方法(此方法现在将value
更改为null
)应该显示错误,但我认为react hook表单无法看到值的变化
如何修复它?您不应该手动重置输入。相反,您应该使用React Hook表单API中的reset()
函数,如下所述:您的clearInput()
无法工作,因为您没有提供唯一的id,因此它找不到要重置的输入元素。因此,请改为:
添加此行以修复
类型={type}
name={name}
ref={register}
/>
但是,还有其他方法可以轻松重置表单,而无需定义自己的重置方法:
- 用于创建重置按钮,重置窗体中的所有字段
- 使用
useForm
hook中的函数重置特定字段:
const{register,reset}=useForm();
返回(
名字
姓
重置({firstName:“默认名称”})
>
重置名字
);
<TexInputComponent
name="title"
defaultValue={data?.title}
register={register({ required: 'Title is required.' })}
error={errors.title}
/>