React Hook Form 7自定义Input组件空值验证报错及Ref警告排查
问题分析与解决
问题现象
自定义Input组件代码:
export type InputProps = { error?: string } & InputHTMLAttributes<HTMLInputElement> export const Input: FunctionComponent<InputProps> = ({ error, ...props }) => ( <input {...props} /> )
结合react-hook-form的使用方式:
<form onSubmit={handleSubmit(onSubmit)}> <Input placeholder="https://example.com" error={errors.url?.message} {...register('url')} /> <input type="submit" /> </form>
出现两个异常:
- URL为空触发验证错误时,调试发现
register('url')仅返回{name: "url"},不符合预期 - 控制台抛出警告:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
原因
react-hook-form的register函数会生成包含ref在内的多组属性,用于获取输入框DOM引用、绑定表单事件。但当前自定义Input组件未处理ref传递——函数组件默认不接收ref,导致ref无法传递到内部原生input元素,react-hook-form无法正常控制表单,因此仅返回name属性,同时触发ref警告。
解决方案
使用React.forwardRef将ref转发到内部原生input元素,修改后的代码如下:
1. 调整组件定义与类型
import React, { forwardRef, InputHTMLAttributes } from 'react'; export type InputProps = { error?: string } & InputHTMLAttributes<HTMLInputElement>; // 用forwardRef转发ref,明确ref指向HTMLInputElement export const Input = forwardRef<HTMLInputElement, InputProps>(({ error, ...props }, ref) => ( <input ref={ref} {...props} /> ));
2. 保持原有使用方式
原表单调用代码无需修改,register返回的ref会被正确传递到内部input元素。
修改完成后,react-hook-form可正常获取input的DOM引用,register会返回完整属性集合,验证逻辑恢复正常,同时ref警告消失。
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

