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

React Hook Form示例遇TS7031错误:label隐式any类型

解决React Hook Form自定义组件的TypeScript类型错误

错误原因

你把组件的返回值类型错误指定为了InputProps,但实际上应该给组件的入参props标注这个类型。TypeScript无法识别props的类型,因此依然抛出implicitly has an 'any' type错误。

修正方案

  1. 调整类型注解位置:将InputProps放在解构参数的后方,而非箭头函数的返回值位置
  2. 替换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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 01:15:41