如何通过打字稿在Formik中添加强类型字段? [英] How to add strongly typed field in Formik by typescript?

查看:68
本文介绍了如何通过打字稿在Formik中添加强类型字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过Typescript在Formik react库中添加强类型,但是我没有这样做.当然,我使用了此链接,但是无法解决我的问题. https://jaredpalmer.com/formik/docs/guides/typescript

I tried to add strongly typed in Formik react library by typescript, but I didn't do that. Of course, I have used this link, but I couldn't solve my issue. https://jaredpalmer.com/formik/docs/guides/typescript

我从这部分代码(})(ActivityForm);中得到了此错误:

I have got this error from this part of code(})(ActivityForm);):

类型'(props:IProps)=>元素'的参数不可分配给 'CompositeComponent类型的参数 & FormikState& FormikHelpers和FormikHandlers& FormikComputedProps& 表格注册与注册{...; }>'.类型'(props:IProps)=>元素'是 不可分配给'FunctionComponent& FormikState& FormikHelpers和FormikHandlers & FormikComputedProps&表格注册与注册{...; }>'.种类 参数"props"和"props"不兼容.财产 类型'FormikSharedConfig< {}>&中缺少'setEditMode'. FormikState & FormikHelpers和FormikHandlers& FormikComputedProps& 表格注册与注册{...; }& {...; }',但必须输入 'IProps'.ts(2345)ActivityForm.tsx(7,3):声明了'setEditMode' 在这里.

Argument of type '(props: IProps) => Element' is not assignable to parameter of type 'CompositeComponent & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }>'. Type '(props: IProps) => Element' is not assignable to type 'FunctionComponent & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }>'. Types of parameters 'props' and 'props' are incompatible. Property 'setEditMode' is missing in type 'FormikSharedConfig<{}> & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; } & { ...; }' but required in type 'IProps'.ts(2345) ActivityForm.tsx(7, 3): 'setEditMode' is declared here.


const ActivityForm:类型的React.FunctionComponent参数 'FunctionComponent'不可分配给类型为参数的参数 'CompositeComponent& FormikState& FormikHelpers和 FormikHandlers& FormikComputedProps& 表格注册与注册{...; }>'.类型"FunctionComponent"为 不可分配给'FunctionComponent& FormikState& FormikHelpers和FormikHandlers& FormikComputedProps&表格注册与注册{...; }>'. 属性"propTypes"的类型不兼容. 输入'WeakValidationMap |未定义"不能分配给类型"WeakValidationMap& FormikState& FormikHelpers和 FormikHandlers& FormikComputedProps& 表格注册与注册{...; }> |不明确的'. 类型"WeakValidationMap"不可分配给类型"WeakValidationMap& FormikState& FormikHelpers和 FormikHandlers& FormikComputedProps& 表格注册与注册{...; }>'. 属性"setFormikState"的类型不兼容. 输入'Validator<(f:FormikState |((prevState:FormikState)=> FormikState), cb ?:(()=> void)|未定义)=> void> |未定义"不可分配 键入'Validator<(f:FormikState |((prevState: FormikState)=> FormikState),cb ?:(()=> 无效)|未定义)=> void> |不明确的'. 输入'Validator<(f:FormikState |((prevState:FormikState)=> FormikState), cb ?:(()=> void)| undefined)=> void>'不可分配给类型 'Validator<(f:FormikState |((prevState: FormikState)=> FormikState),cb ?:(()=> 无效)|未定义)=> void>'. 类型'(f:FormikState |((prevState:FormikState)=> FormikState),cb ?:(()=> 无效)| undefined)=> void'不能分配给类型'(f: FormikState | ((prevState:FormikState)=> FormikState),cb ?:(()=> void)|未定义)=>无效". 参数"f"和"f"的类型不兼容. 输入'FormikState | (((prevState:FormikState)=> FormikState)'不是 可分配给类型'FormikState | ((prevState: FormikState)=> FormikState)'. "FormikState"类型不能分配给"FormikState | Type". ((prevState: FormikState)=> FormikState)'. 类型"FormikState"不能分配给类型"FormikState".ts(2345)偷看问题 没有快速修复程序

const ActivityForm: React.FunctionComponent Argument of type 'FunctionComponent' is not assignable to parameter of type 'CompositeComponent & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }>'. Type 'FunctionComponent' is not assignable to type 'FunctionComponent & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }>'. Types of property 'propTypes' are incompatible. Type 'WeakValidationMap | undefined' is not assignable to type 'WeakValidationMap & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }> | undefined'. Type 'WeakValidationMap' is not assignable to type 'WeakValidationMap & FormikState & FormikHelpers & FormikHandlers & FormikComputedProps & FormikRegistration & { ...; }>'. Types of property 'setFormikState' are incompatible. Type 'Validator<(f: FormikState | ((prevState: FormikState) => FormikState), cb?: (() => void) | undefined) => void> | undefined' is not assignable to type 'Validator<(f: FormikState | ((prevState: FormikState) => FormikState), cb?: (() => void) | undefined) => void> | undefined'. Type 'Validator<(f: FormikState | ((prevState: FormikState) => FormikState), cb?: (() => void) | undefined) => void>' is not assignable to type 'Validator<(f: FormikState | ((prevState: FormikState) => FormikState), cb?: (() => void) | undefined) => void>'. Type '(f: FormikState | ((prevState: FormikState) => FormikState), cb?: (() => void) | undefined) => void' is not assignable to type '(f: FormikState | ((prevState: FormikState) => FormikState), cb?: (() => void) | undefined) => void'. Types of parameters 'f' and 'f' are incompatible. Type 'FormikState | ((prevState: FormikState) => FormikState)' is not assignable to type 'FormikState | ((prevState: FormikState) => FormikState)'. Type 'FormikState' is not assignable to type 'FormikState | ((prevState: FormikState) => FormikState)'. Type 'FormikState' is not assignable to type 'FormikState'.ts(2345) Peek Problem No quick fixes available


此错误来自ActivityDashboard.tsx

键入'{setEditMode:(editMode:boolean)=> void; title:字符串; 描述:字符串;类别:字串;城市:字串;地点:字符串; 日期:字符串; }'缺少类型中的以下属性 "IProps":值,错误,被触摸,isSubmitting和另外28个.ts(2740)

Type '{ setEditMode: (editMode: boolean) => void; title: string; description: string; category: string; city: string; venue: string; date: string; }' is missing the following properties from type 'IProps': values, errors, touched, isSubmitting, and 28 more.ts(2740)


import React from "react";
import * as yup from "yup";
import { withFormik, Form, Field, FormikProps } from "formik";


interface IProps {
  setEditMode: (editMode: boolean) => void;
}

export const ActivityForm = (props: IProps) => {
  const { setEditMode } = props;
  return (
    <Form>
      <Field type="text" name="title" placeholder="Title" />
      <Field
        type="text"
        rows={2}
        name="description"
        placeholder="Description"
      />
      <Field type="text" name="category" placeholder="Category" />
      <Field type="date" name="date" placeholder="Date" />
      <Field type="text" name="city" placeholder="City" />
      <Field type="text" name="venue" placeholder="Venue" />
      <button type="submit">Edit</button>
      <button type="button" onClick={() => setEditMode(false)}>
        Cancel
      </button>
    </Form>
  );
};

const myForm = withFormik({
  mapPropsToValues: props => {
    return {};
  },
  validationSchema: yup.object().shape({
    title: yup.string().required()
  }),
  handleSubmit(values) {
    console.log(values);
  }
})(ActivityForm);

export default myForm;


import React from "react";
import { IActivity } from "../../../app/models/activity";
import { ActivityList } from "./ActivityList";
import { Col, Row } from "antd";
import { ActivityDetails } from "../details/ActivityDetails";
import { ActivityForm } from "../form/ActivityForm";

interface IProps {
  activities: IActivity[];
  selectActivity: (id: string) => void;
  selectedActivity: IActivity | null;
  editMode: boolean;
  setEditMode: (editMode: boolean) => void;
  setSelectedActivity: (activity: IActivity | null) => void;
}

export const ActivityDashboard: React.FC<IProps> = ({
  activities,
  selectActivity,
  selectedActivity,
  editMode,
  setEditMode,
  setSelectedActivity
}) => {
  return (
    <Row>
      <Col span={3}></Col>
      <Col span={10}>
        <ActivityList activities={activities} selectActivity={selectActivity} />
      </Col>
      <Col span={1}></Col>
      <Col span={6}>
        {selectedActivity && !editMode && (
          <ActivityDetails
            activity={selectedActivity}
            setEditMode={setEditMode}
            setSelectedActivity={setSelectedActivity}
          />
        )}
        {editMode && (
          <ActivityForm
            setEditMode={setEditMode}
            title="alex"
            description="hi"
            category="human"
            city="newyork"
            venue="sd"
            date="2019"
          />
        )}
      </Col>
    </Row>
  );
};

推荐答案

我认为这里存在多个问题,这些问题会导致TypeScript编译器产生混乱的消息:

I think there are multiple issues here which causes the confusing message from the TypeScript compiler:

  1. 首先,请确保您的功能组件扩展了React.FC<Props>类型,以便TypeScript知道这是一个React组件:

  1. First of all, make sure that your functional component extends the React.FC<Props> type so that TypeScript knows that this is a React component:

import * as React from 'react';

export const ActivityForm : React.FC<IProps> = (props) => {
...

  • 然后您必须从formik包中将IProps类型扩展为FormikProps类型,因为withFormik方法仅接受支持从该类型扩展了其支持的React组件. :

  • Then you have to extend your IProps-type with the FormikProps-type from the formik package, because the withFormik-method only accepts React-components whose props are extend from this type:

    import { FormikProps } from 'formik';
    
    interface MyFormValues {
      title: string;
      category: string;
      description: string;
    }
    
    interface IProps extends FormikProps<MyFormValues> {
      setEditMode(arg: boolean): void;
    }
    

  • 然后,您的最终代码应如下所示(确保将缺少的属性添加到MyFormValues界面中):

    Your final code should then look like this (Make sure to add the missing properties to the MyFormValues interface):

    import * as React from 'react';
    import { withFormik, Form, Field, FormikProps } from 'formik';
    import * as Yup from 'yup';
    
    interface MyFormValues {
      title: string;
      category: string;
      description: string;
      ...
    }
    
    interface IProps extends FormikProps<MyFormValues> {
      setEditMode(arg: boolean): void;
    }
    
    export const ActivityForm: React.FC<IProps> = props => {
      const { setEditMode } = props;
      return (
        <Form>
          <Field type="text" name="title" placeholder="Title" />
          <Field
            type="text"
            rows={2}
            name="description"
            placeholder="Description"
          />
          <Field type="text" name="category" placeholder="Category" />
          <Field type="date" name="date" placeholder="Date" />
          <Field type="text" name="city" placeholder="City" />
          <Field type="text" name="venue" placeholder="Venue" />
          <button type="submit">Edit</button>
          <button type="button" onClick={() => setEditMode(false)}>
            Cancel
          </button>
        </Form>
      );
    };
    
    const myForm = withFormik({
      mapPropsToValues: props => {
        return {};
      },
      validationSchema: Yup.object().shape({
        title: Yup.string().required()
      }),
      handleSubmit(values) {
        console.log(values);
      }
    })(ActivityForm);
    
    export default myForm;
    

    这里还有一个带有最终代码的CodeSandbox: https: //codesandbox.io/s/stackoverflow59057524-s9ouc?module=%2Fsrc%2FActivityForm.tsx

    Also here is a CodeSandbox with the final code: https://codesandbox.io/s/stackoverflow59057524-s9ouc?module=%2Fsrc%2FActivityForm.tsx

    这篇关于如何通过打字稿在Formik中添加强类型字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆