动态控制通用反应钩形式。收到错误 TS2322:类型"控件<表单字段,任意>"不能分配给类型"控件<字段值,任何>



在我的应用程序中,我使用最新版本的MUI 5.11的react-hook形式。我已经创建了可重用的Select组件:

...someImports
import { Control, Controller } from 'react-hook-form';
interface SelectProps {
control: Control;
...someProps
}
export interface SelectOption {
title: string;
value: any;
}
const Select: FC<SelectProps> = ({
...props
}) => {
return (
<Controller
control={control}
name={name}
render={({ field }) => (
<FormControl {...props} fullWidth>
<InputLabel id={label}>{label}</InputLabel>
<MuiSelect
..someOptions
>
{options.map((option) => (
<MenuItem value={option.value}>{option.title}</MenuItem>
))}
</MuiSelect>
</FormControl>
)}
/>
);
};
export default Select;

当我在组件中使用它时,我得到一个Typescript错误:

TS2322: Type 'Control<FormFields,>'是不可赋值的type 'Control<FieldValues,>'.

interface FormFields {
name: string;
age: number;
}
const { control, handleSubmit, setValue, watch } = useForm<FormFields>()
<Grid container columnGap={5} alignItems="stretch" sx={{ width: '500px' }}>
<Grid xs={4}>
<Select
control={control} - here I pass control and this is where control is red-underlined

我尝试了一些游戏-没有帮助:(

这是因为,SelectProps中的controlreact-hook-form中输入为Control。在你的网格中,你从useForm钩子中传递了解构的control,它的类型是从FormFields中推断出来的。

由于这两种类型不同,因此抛出TS错误。用FieldValues扩展FormValues

interface FormFields extends FieldValues {
name: string;
age: number;
}

或将SelectProps更新为

interface SelectProps {
control: Control<FormValues>;
...someProps
}

文档:https://react-hook-form.com/ts控制

相关内容

最新更新