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

React Hook Form绑定自定义组件时出现TypeScript类型不兼容错误

解决react-hook-form Controller与ReactPrime控件绑定的TypeScript类型不兼容问题

这个错误的核心是Controller默认泛型为FieldValues,但你的control是Control<ConfigureData>类型,二者的Resolver参数不兼容。解决方法是给Controller显式指定与useForm一致的泛型,并补充必填的name属性:

修正后的Controller使用代码

<Controller<ConfigureData>
  control={control}
  // 必须指定对应ConfigureData中的字段名
  name="isWorkingMonday"
  render={({ field, fieldState }) => (
    // 正确映射ReactPrime InputSwitch的属性到react-hook-form的field对象
    <InputSwitch
      checked={field.value}
      onChange={(e) => field.onChange(e.checked)}
      disabled={fieldState.isDisabled}
    />
  )}
/>

关键说明

  1. 显式泛型声明:给Controller加上<ConfigureData>泛型,让它知道表单的具体类型,从而和useForm返回的control类型完全匹配。
  2. 必填name属性:Controller必须指定name,值必须是ConfigureData中定义的字段(比如isWorkingMonday、title等),这是react-hook-form追踪表单字段的核心标识。
  3. 控件属性映射:ReactPrime的InputSwitch需要手动将field.value绑定到checked,将field.onChange绑定到组件的onChange事件(注意转换参数格式,InputSwitch的onChange返回的是事件对象,需要取e.checked)。

完整上下文示例

import { useForm, Controller } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { InputSwitch } from 'primereact/inputswitch';

type ConfigureData = {
  title: string;
  description: string;
  startHour: number;
  endHour: number;
  isWorkingMonday: boolean;
  isWorkingTuesday: boolean;
  isWorkingWednesday: boolean;
  isWorkingThursday: boolean;
  isWorkingFriday: boolean;
  isWorkingSaturday: boolean;
  isWorkingSunday: boolean;
};

const schema = yup
  .object({
    title: yup.string().required(),
    description: yup.string().required(),
  })
  .required();

export const ConfigureForm = () => {
  const {
    control,
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ConfigureData>({ 
    resolver: yupResolver(schema), 
    defaultValues: { isWorkingMonday: true } 
  });

  const onSubmit = (data: ConfigureData) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* 文本字段示例 */}
      <input {...register('title')} placeholder="标题" />
      {errors.title && <span style={{color: 'red'}}>标题不能为空</span>}

      {/* 修正后的InputSwitch绑定 */}
      <Controller<ConfigureData>
        control={control}
        name="isWorkingMonday"
        render={({ field, fieldState }) => (
          <div style={{margin: '1rem 0'}}>
            <label>周一工作</label>
            <InputSwitch
              checked={field.value}
              onChange={(e) => field.onChange(e.checked)}
            />
          </div>
        )}
      />

      <button type="submit">提交配置</button>
    </form>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:35:31