【问题标题】:React Native Typescript Formik typings of handleSubmit in onPress在 onPress 中反应原生 Typescript Formik 的 handleSubmit 类型
【发布时间】:2020-04-23 05:29:01
【问题描述】:

我刚刚开始使用 Typescript 在 React Native 上开展一个项目,并跟随 Formik 在我的应用程序中构建表单。

我做了很棒的formik tutorial guide 并看到了formik with RN section in JS 的使用。

但是,当我尝试将此示例翻译成打字稿时,我在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&lt;HTMLFormElement&gt;) =&gt; void 接受来自表单提交的事件(onSubmit 元素的onSubmit 属性)。由于 RN 中没有等效的 Form,它抱怨从 RN Button's onPress 属性接收到 (ev: NativeSyntheticEvent&lt;NativeTouchEvent&gt;) =&gt; void

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

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

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

CodeSandbox: App.tsx:32

感谢您的帮助。

【问题讨论】:

    标签: typescript forms react-native typescript-typings formik


    【解决方案1】:

    你可以这样描述你的类型:(event: GestureResponderEvent) =&gt; void;

    Code sample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      相关资源
      最近更新 更多