React Native Typescript在onPress中生成handleSubmit的类型

prdp8dxp  于 2023-04-22  发布在  React
关注(0)|答案(2)|浏览(167)

我刚开始用Typescript在React Native上做了一个项目,为了在我的应用程序中构建表单,我沿着Formik。
我做了很棒的formik tutorial guide,看到了formik with RN section in JS的使用。
然而,当我试图将这个例子翻译成typescript时,我在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...

据我所知,handleSubmit函数(e?: FormEvent<HTMLFormElement>) => void,接受来自表单提交的事件(form元素的onSubmit属性)。由于RN中没有Form等价物,它会抱怨从RN Button's onPress属性接收(ev: NativeSyntheticEvent<NativeTouchEvent>) => void
为了摆脱错误并继续前进,我使用了以下解决方案,但我并不满意:

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

我想知道我应该怎样正确地解决这个打字错误。
CodeSandbox: App.tsx:32
谢谢你的帮助。

ttisahbt

ttisahbt1#

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

ldxq2e6h

ldxq2e6h2#

我通常这样做:

<Pressable onPress={(e:any) => formik.handleSubmit(e)}>

相关问题