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

React Hook Form提交时值为undefined问题求助

问题原因与修复方案

核心问题

你的自定义TextInput组件没有使用React.forwardRef转发引用,导致React Hook Form通过register返回的ref无法绑定到内部的<Input>元素上。React Hook Form依赖这个ref来访问输入元素的value,无法获取引用时,提交自然会返回undefined。

修复步骤

  1. 修改TextInput组件,添加ref转发
    使用React.forwardRef包裹组件,将外部传入的ref直接传递给内部的<Input>元素:
import React, { forwardRef } from 'react';

const TextInput = forwardRef(({ label, id, placeholder, name, ...params }, ref) => {
  return (
    <FormGroup>
      <Label htmlFor={id}> {label} </Label>
      <Input
        className="form-control"
        placeholder={placeholder}
        name={name}
        id={id}
        ref={ref}
        {...params}
      />
    </FormGroup>
  );
});

export default TextInput;
  1. 优化组件调用(可选但推荐)
    register("password")返回的对象已经包含name属性,无需手动传递name="password",避免重复配置:
<form onSubmit={handleSubmit(onSubmit)}>
  <TextInput
    label="input password"
    placeholder="password"
    {...register("password")}
    id="password"
    type="password"
  />
  <button type="submit">submit</button>
</form>

原理说明

React Hook Form v7的register方法会生成包含ref、onChange、onBlur、name的对象,其中ref是核心——它让库能直接访问原生输入元素的DOM节点,从而读取和同步输入值。自定义组件如果不转发ref,这个引用会被组件本身拦截,无法传递到内部的输入控件,最终导致表单无法收集值。

内容的提问来源于stack exchange,提问作者Nika Simon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:15:34