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

WebStorm/React Hook Form为何不提示name参数可选值?

解决React Hook Form中输入框name参数无类型提示的问题

你的问题核心是Form组件没有传递表单的字段类型信息,导致子组件StringInput无法通过useFormContext关联到你定义的Data类型,所以name参数没有自动提示可选字段。

具体修改方案

1. 改造Form组件,支持泛型传递类型

给Form组件添加泛型,让它携带表单的字段类型信息,确保上下文能识别到具体的字段结构:

import { FormProvider, UseFormReturn } from "react-hook-form";

export const Form = <TFieldValues extends Record<string, any>>({
  children,
  form,
}: {
  children: React.ReactNode;
  form: UseFormReturn<TFieldValues>;
}) => {
  return <FormProvider {...form}>{children}</FormProvider>;
};

2. 调整StringInput组件,从上下文自动获取类型

不需要在StringInput里单独声明泛型,直接通过useFormContext自动获取当前表单的字段类型,这样name参数会自动关联到Data的可选字段:

import { useFormContext, Controller, FieldPath } from "react-hook-form";

export const StringInput = ({ 
  name 
}: { 
  name: FieldPath<ReturnType<typeof useFormContext>['_formValues']> 
}) => {
  const { control } = useFormContext();
  return (
    <Controller
      name={name}
      control={control}
      render={({ field }) => <input {...field} />}
    />
  );
};

3. App组件保持原有写法即可

当你用useForm<Data>()创建表单实例并传递给Form组件后,Form的泛型会自动推断为Data类型,子组件StringInput就能通过上下文精准识别字段,此时输入name参数时就会出现'name'和'num'的智能提示。

原写法失效原因

原来的Form组件没有携带具体的类型信息,useFormContext只能识别宽泛的FieldValues类型,无法关联到你定义的Data结构,自然无法给出字段提示。通过给Form组件添加泛型传递类型,上下文就能携带具体的字段结构,子组件也就能获取到精准的类型提示。

内容的提问来源于stack exchange,提问作者i chestor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 18:05:14