使用React Hook Form时通用输入组件无法捕获用户输入数据的问题求助
使用React Hook Form时通用输入组件无法捕获用户输入数据的问题求助
嘿,我之前在做React Hook Form自定义组件的时候也踩过这个坑,你的问题大概率是TypeScript类型定义没处理好,导致React Hook Form的register返回的关键属性没被正确传递到input元素上。
让我一步步拆解问题和解决方案:
问题根源
你用TypeScript定义了TextInputProps,但如果这个类型没有继承原生input元素的属性,那么...inputProps就会丢失register传递的name、onChange、onBlur这些核心属性——而React Hook Form正是靠这些属性来追踪表单值的。没有这些属性,表单自然捕获不到用户输入,提交时就会返回undefined。
另外还有个小细节问题:你的错误提示写的是error.message(字符串字面量),应该改成{error.message}才能显示实际的错误文本,不过这不是导致数据丢失的原因。
解决方案
1. 修正TypeScript类型定义
让TextInputProps继承原生input的所有属性,这样register返回的props就能被正确接收和传递:
// 先导入需要的类型 import { FieldError } from "react-hook-form"; type TextInputProps = { label: string; className?: string; error?: FieldError; } & React.InputHTMLAttributes<HTMLInputElement>;
2. 修正错误提示的渲染
把错误提示里的字符串字面量改成变量引用:
{error && <div className="error">{error.message}</div>}
3. 确认组件属性传递正确
你的组件里input标签的{...inputProps}写法是对的,只要类型定义修正后,register的name、onChange等属性就会被正确传递到input上。
修改后的完整TextInput组件示例
import React from "react"; import { FieldError } from "react-hook-form"; // 假设你已经导入了Styled Components的InputContainer type TextInputProps = { label: string; className?: string; error?: FieldError; } & React.InputHTMLAttributes<HTMLInputElement>; function TextInput({ label, className, error, ...inputProps }: TextInputProps) { const inputId = React.useId(); return ( <InputContainer className={className} error={!!error}> <label className="label" htmlFor={inputId}> {label} </label> <input className="input" id={inputId} type="text" {...inputProps} /> {error && <div className="error">{error.message}</div>} </InputContainer> ); }
这样修改后,再提交表单应该就能正常捕获到用户输入的数据了!
备注:内容来源于stack exchange,提问作者hcotta
相关产品推荐
相关产品推荐

