react-hook-form 中 handleSubmit 参数的类型

Type of handleSubmit parameter in react-hook-form

我在 handleSubmit 函数中遇到 TypeScript 错误。

  1. 我正在通过 useForm:
  2. 检索 handleSubmit 函数
const {handleSubmit, control, watch, reset} = useForm()
  1. 我正在定义提交功能:
const submit = (data: { file: File, crop: Area }) => {
    onSubmit(data.file, data.crop)  // onSubmit is passed from parent component
}
  1. 我在 Form 组件的 onSubmit prop 中传递了 handleSubmit
<Form onSubmit={handleSubmit(submit)}>
    // registering form fields here
</Form>
  1. 出现以下 TypeScript 错误:
 Argument of type '(data: {    file: File;    crop: Area;}) => void' is not assignable to parameter of type 'SubmitHandler<FieldValues>'.
[1]   Types of parameters 'data' and 'data' are incompatible.
[1]     Type '{ [x: string]: any; }' is missing the following properties from type '{ file: File; crop: Area; }': file, crop  TS2345

如果我像这样通过 handleSubmit 一切正常。

<Form onSubmit={handleSubmit(submit as any)}></Form>

但我尽量不在我的项目中使用 any。因此,如果有人可以解释我应该如何为 handleSubmit 函数键入参数,我会很感激。 ;)

您可以将添加到 submit() 函数的 data 的相同类型添加到 useForm 挂钩。

因此在您的示例中,您可以创建一个新类型:

type Data = { 
  file: File; 
  crop: Area;
}

并将其传递给两者,submit() 函数:

const submit = (data: Data) => {
// ...

useForm()挂钩:

const {handleSubmit, control, watch, reset} = useForm<Data>()

那么应该可以了:)

据我了解,提供给 submit() 数据的类型仅提供有关键入 submit() 函数的信息。

但是因为这个函数也是作为参数传递给handleSubmit()handleSubmit()需要知道传递给submit()的数据类型。我们可以让它知道这种类型,只需将其提供给 useForm 挂钩即可。