首页 > 解决方案 > react-hook-form 无法通过单击按钮重置输入来查看更改值

问题描述

带有输入和重置输入按钮的组件TexInputComponent

<input
    type={type}
    name={name}
    ref={register}
/>
<button
    type="button"
    onClick={clearInput}>
Reset input
</button>

const clearInput = () => {
  document.querySelector(`#${name}`).value = null;
};

TexInputComponent在另一个组件中使用内部表单:

  <TexInputComponent
    name="title"
    defaultValue={data?.title}
    register={register({ required: 'Title is required.' })}
    error={errors.title}
  />

现在,当我单击表单上的提交时,react-hook-form返回错误,例如“需要标题!”。当我在 中写东西时TexInputComponent,错误就会消失。问题是当我编写文本并单击按钮以重置输入时。该clearInput方法已执行(此方法更改valuenull)现在应该显示错误,但我认为反应钩子形式看不到值发生变化。

我该如何解决?

标签: reactjsreact-hook-form

解决方案


clearInput()不起作用,因为您没有提供唯一的 id,因此它无法找到要重置的输入元素。所以改成这样:

<input
    id={name} // --> add this line to fix
    type={type}
    name={name}
    ref={register}
/>

但是,还有其他方法可以轻松重置表单,而无需定义自己的重置方法:

const { register, reset } = useForm();

return (
  <form onSubmit={handleSubmit(onSubmit)}>
    <label>First name</label>
    <input type="text" name="firstName" ref={register} />

    <label>Last name</label>
    <input type="text" name="lastName" ref={register} />

    <input type="submit" />
    <button
      type="button"
      onClick={() => reset({ firstName: "default name" })}
    >
      Reset first name
    </button>
  </form>
);

推荐阅读