React Hook Form示例遇TS7031错误:label隐式any类型
解决React Hook Form自定义组件的TypeScript类型错误
错误原因
你把组件的返回值类型错误指定为了InputProps,但实际上应该给组件的入参props标注这个类型。TypeScript无法识别props的类型,因此依然抛出implicitly has an 'any' type错误。
修正方案
- 调整类型注解位置:将
InputProps放在解构参数的后方,而非箭头函数的返回值位置 - 替换
any为精确类型,贴合React和React Hook Form的类型规范:onChange用React.ChangeEventHandler<HTMLInputElement>onBlur用React.FocusEventHandler<HTMLInputElement>ref用React.Ref<HTMLInputElement>
完整修正代码
import React from 'react'; const options = [ { value: 'chocolate', label: 'Chocolate' }, { value: 'strawberry', label: 'Strawberry' }, { value: 'vanilla', label: 'Vanilla' }, ]; interface InputProps { label: string; name: string; onChange: React.ChangeEventHandler<HTMLInputElement>; onBlur: React.FocusEventHandler<HTMLInputElement>; ref: React.Ref<HTMLInputElement>; } const MyInput = ({ label, name, onChange, onBlur, ref }: InputProps) => { return ( <> <label htmlFor={name}>{label}</label> <input name={name} placeholder="Jane" onChange={onChange} onBlur={onBlur} ref={ref} /> </> ); };
补充说明
Next.js不会引发这个问题,这是TypeScript类型注解的基础用法错误。如果需要更贴合React Hook Form的自定义组件规范,还可以结合库提供的Controller组件与FieldValues类型,但上述修正已能解决当前的类型报错。
内容的提问来源于stack exchange,提问作者a7dc
相关产品推荐
相关产品推荐

