【问题标题】:React hook form useController typescript type error反应钩子形式useController打字稿类型错误
【发布时间】:2021-12-17 11:30:06
【问题描述】:

我试图在这个例子中拆分代码: https://codesandbox.io/s/usecontroller-0o8px

但是当我将control={control} 传递给输入组件时出现类型错误。

(JSX attribute) control?: Control<FieldValues, object> | undefined
Type 'Control<formValues, object>' is not assignable to type 'Control<FieldValues, object>'.
  The types of '_options.resolver' are incompatible between these types.
    Type 'Resolver<formValues, object> | undefined' is not assignable to type 'Resolver<FieldValues, object> | undefined'.
      Type 'Resolver<formValues, object>' is not assignable to type 'Resolver<FieldValues, object>'.ts(2322)
controller.d.ts(22, 5): The expected type comes from property 'control' which is declared here on type 'IntrinsicAttributes & { label?: string | undefined; supportive?: string | undefined; } & UseControllerProps<FieldValues, string> & InputHTMLAttributes<...> & { ...; }'

这是我的输入组件

type Props = {
  label?: string
  supportive?: string
} & UseControllerProps &
  InputHTMLAttributes<HTMLInputElement>

const InputComp: FC<Props> = ({ label, supportive, ...props }) => {

  ...

  const {
    field,
    fieldState: { invalid, isTouched, isDirty },
    formState: { touchedFields, dirtyFields },
  } = useController(props)

  return <input {...field} />
}

当我将 formValues 类型传递给 UseControllerProps&lt;formValues&gt; 时,错误消失了。

我想用不同的formValues来使用不同形式的输入组件,我该如何实现呢?

【问题讨论】:

  • 找到解决办法了吗?
  • 是的,我使用了泛型类型。我的组件现在看起来像这样:type Props&lt;T&gt; = {..} &amp; UseControllerProps&lt;T&gt;function InputComp&lt;T&gt;(props: Props&lt;T&gt;) {} 然后在表单中,我传递 类型,如下所示:&lt;Input&lt;FormType&gt; name='title' type='text' control={control} /&gt;

标签: reactjs typescript react-hook-form


【解决方案1】:

我遇到了同样的问题,但我找到了这篇文章,这个人通过一个在组件中扩展的 T 道具解决了这个问题

https://dev.to/texmeijin/component-design-idea-using-react-hook-form-v7-ie0

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2021-09-04
  • 2021-06-30
  • 2021-01-03
  • 2017-10-30
  • 2021-07-09
  • 1970-01-01
  • 2021-08-30
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多