You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用自定义组件时React Hook Form的register函数失效问题

解决React Hook Form register在自定义输入组件失效的问题

核心问题是你没把register返回的所有必要属性(比如name、onChange、onBlur)透传给自定义组件内部的原生input元素。

修复步骤:

  1. 改造自定义输入组件,让它接收并透传所有原生input的属性:
import React from 'react';

// 继承原生input的所有属性类型
type CustomInputProps = React.InputHTMLAttributes<HTMLInputElement>;

const CustomInput = ({ ...props }: CustomInputProps) => {
  // 把所有props直接传给内部的原生input
  return <input {...props} />;
};

export default CustomInput;
  1. 在表单中使用时,直接将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:50:45