React Native Typescript Formik 在 onPress 中输入 handleSubmit

Phi*_*lou 5 forms typescript react-native typescript-typings formik

我刚刚启动了一个使用 Typescript 的 React Native 项目,并使用 Formik 来在我的应用程序中构建表单。

我做了很棒的formik 教程指南,并看到了formik 与 JS 中 RN 部分的使用。

但是,当我尝试将此示例翻译为打字稿时,我在以下位置出现了以下键入错误Button's onPress attribute

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.
    Type '(e?: FormEvent<HTMLFormElement>) => 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>'.
          Types of property 'nativeEvent' are incompatible.
            Type 'NativeTouchEvent' is missing the following properties from type 'Event': bubbles, cancelBubble, cancelable, composed, and 17 more.
  Overload 2 of 2, '(props: ButtonProps, context?: any): Button', gave the following error.
    Type '(e?: FormEvent<HTMLFormElement>) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.ts(2769)
index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps> & Readonly<{ children?: ReactNode; }>'
index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAt...

Run Code Online (Sandbox Code Playgroud)

据我了解,该handleSubmit函数(e?: FormEvent<HTMLFormElement>) => void接受来自表单提交(元素onSubmit的属性form)的事件。由于 RN 中没有等效的 Form,因此它抱怨(ev: NativeSyntheticEvent<NativeTouchEvent>) => voidRN Button's onPress属性接收 。

为了摆脱错误并继续,我使用了以下我不满意的解决方法:

 <Button
              title="Do it !"
              color={colors.red}
              onPress={
                (handleSubmit as unknown) as (
                  ev: NativeSyntheticEvent<NativeTouchEvent>
                ) => void
              }
/>
Run Code Online (Sandbox Code Playgroud)

我想知道我应该如何正确解决这个打字错误。

CodeSandbox:App.tsx:32

感谢您的帮助。

小智 2

您可以这样描述您的类型:(event: GestureResponderEvent) => void;

代码示例