使用自定义组件时React Hook Form的register函数失效问题
解决React Hook Form register在自定义输入组件失效的问题
核心问题是你没把register返回的所有必要属性(比如name、onChange、onBlur)透传给自定义组件内部的原生input元素。
修复步骤:
- 改造自定义输入组件,让它接收并透传所有原生input的属性:
import React from 'react'; // 继承原生input的所有属性类型 type CustomInputProps = React.InputHTMLAttributes<HTMLInputElement>; const CustomInput = ({ ...props }: CustomInputProps) => { // 把所有props直接传给内部的原生input return <input {...props} />; }; export default CustomInput;
- 在表单中使用时,直接将
register的返回值展开传给自定义组件:
<CustomInput {...register('yourFieldName')} />
如果你的自定义组件需要额外的自定义属性(比如标签、自定义样式),可以扩展类型并保留透传逻辑:
type CustomInputProps = React.InputHTMLAttributes<HTMLInputElement> & { label?: string; }; const CustomInput = ({ label, ...props }: CustomInputProps) => { return ( <div className="input-group"> {label && <label htmlFor={props.id}>{label}</label>} <input {...props} className="custom-styled-input" /> </div> ); };
这样React Hook Form就能正常追踪输入值的变化,和使用原生input的效果完全一致。
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

