reactjs - 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
方法已执行(此方法更改value
为null
)现在应该显示错误,但我认为反应钩子形式看不到值发生变化。
我该如何解决?
解决方案
您clearInput()
不起作用,因为您没有提供唯一的 id,因此它无法找到要重置的输入元素。所以改成这样:
<input
id={name} // --> add this line to fix
type={type}
name={name}
ref={register}
/>
但是,还有其他方法可以轻松重置表单,而无需定义自己的重置方法:
用于
<input type='reset' />
创建重置表单中所有字段的重置按钮。使用钩子中的
reset()
函数useForm
重置特定字段:
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>
);
推荐阅读
- javascript - 在 React 中调用从父组件到子组件的方法传递
- node.js - 如何将 Knex 日期设置为未来 30 天
- flutter - 未处理的异常:内容大小低于指定的 contentLength。已写入 206 字节,但预期为 375482。#228
- reactjs - 反应测试 getByText 不适用于 p 元素
- python - 在数据框中组织收集的条目
- python - TypeError:字符串索引必须是复杂 json 数组中的整数
- cassandra - Cassandra 中的堆内存默认分配
- reactjs - 使用 react-cookie setCookie 的打字稿错误 - 类型 '{ [name: string]: any; }' 没有兼容的调用签名.ts(2349)
- dart - 如何使用 ngFor 遍历组件列表
- android - 具有嵌套 RecyclerViews 和双向滚动的 ScrollView