React Native Typescript Formik 转换事件类型

mah*_*man 8 type-conversion typescript reactjs react-native formik

在 React Native 的 Formik 文档中,有一个示例表单:

<Formik initialValues={{ email: '' }} onSubmit={(values) => console.log(values)}>
  {({ handleChange, handleBlur, handleSubmit, values }) => (
    <View>
      <TextInput onChangeText={handleChange('email')} onBlur={handleBlur('email')} value={values.email} />
      <Button onPress={handleSubmit} title="Submit" />
    </View>
  )}
</Formik>
Run Code Online (Sandbox Code Playgroud)

然而,这给了我一个打字稿错误:

No overload matches this call.
Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.
  Type '(e?: FormEvent<HTMLFormElement> | undefined) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.
    Types of parameters 'e' and 'ev' are incompatible.
      Type 'NativeSyntheticEvent<NativeTouchEvent>' is not assignable to type 'FormEvent<HTMLFormElement>'.
Run Code Online (Sandbox Code Playgroud)

鉴于我从解构中获取了handleSubmit 函数,如何正确转换事件类型?

注意:我知道我可以做到这一点,但我已经读到这将导致 React 中出现额外的渲染:

<Button onPress={(e) => handleSubmit(e as any)} title="Submit" />
Run Code Online (Sandbox Code Playgroud)

小智 5

也许这不是最好的,但你可以做这样的事情

  <Button
     onPress={handleSubmit as (values: any) => void} // <= add this
     title="Submit" />
Run Code Online (Sandbox Code Playgroud)