Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应钩形罐';单击按钮重置输入,看不到更改值_Reactjs_React Hook Form - Fatal编程技术网

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}
  />