【发布时间】: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<formValues> 时,错误消失了。
我想用不同的formValues来使用不同形式的输入组件,我该如何实现呢?
【问题讨论】:
-
找到解决办法了吗?
-
是的,我使用了泛型类型。我的组件现在看起来像这样:
type Props<T> = {..} & UseControllerProps<T>function InputComp<T>(props: Props<T>) {}然后在表单中,我传递类型,如下所示: <Input<FormType> name='title' type='text' control={control} />
标签: reactjs typescript react-hook-form