打字稿 |在 IProps 上扩展 formikProps 时,Typescript 缺少 27 个 Props

Typescript | Typescript is missing 27 Props, when extending formikProps on IProps

我在 TypeScript 中使用 Formik,我想在 TS 中使用一个非常简单的表单组件,在另一个组件中,我从中获取 defaultValuesvalidationSchemas.

棘手的部分是如何只访问所需的 formikProps,而不是出现以下错误:

Type '{}' is missing the following properties from type 'Readonly<IProps>': values, errors, touched, isValidating, and 25 more.ts(2740)
(alias) class PasswordFields
import PasswordFields

组件代码如下:

interface IProps extends FormikProps<IValues> {
  username?: string;
  email?: string;
}

interface IValues {
  username?: string;
  email?: string;
}

在主要组件中我这样称呼它:

render(): ReactNode {
    const { mode } = this.props;
    return (
      <Formik
        initialValues={this.getInitialValues()}
        validationSchema={this.getValidationSchemas()}
        onSubmit={this.handleSubmit}
        validateOnBlur={false}
        render={({ isSubmitting, status }) =>
          (
            <Form>
              {mode === ActionMode.EDIT_INFO && (
                <Fragment>
                  <InfoFields /> // I am getting the error here..
                  <GroupSelectField />
                </Fragment>
              )}
              <Button
                className="btn btn-primary w-100 mt-5"
                disabled={isSubmitting}
                loading={isSubmitting}
                type="submit"
              >
                {mode === ActionMode.EDIT_INFO && <span>UPDATE INFO</span>}
              </Button>
            </Form>
          ) as ReactNode
        }
      />
    );
  }

我对此有点了解。你能告诉我如何只访问我想要的 formikProps,这样 TS 就不会抱怨了吗??我还有另一个问题。如何将 props 从组件传递到 formik 表单。

与具有相同问题的 your other question 一样,InfoFields 期待您没有传递的道具:

<Formik
    render={formikProps => (
        <Form>
            // Other Code.

            <InfoFields {...formikProps} />

            // Other Code.
        </Form>
    )}
/>

Could you tell me how to access only the formikProps that I want, so TS, doesn't complain

您可以 select 从 FormikProps 中获取您真正想要的道具,然后将它们传递给 InfoFields,而不是上面的内容。例如这样的事情:

const InfoFields = ({ errors, touched }: Pick<FormikProps<IValues>, 'errors' | 'touched'>) => (
    <div>
        // Whatever.
    </div>
);

... 并在父组件中呈现为:

<Formik
    render={({ errors, touched }) => (
        <Form>
            // Other Code.

            <InfoFields errors={errors} touched={touched} />

            // Other Code.
        </Form>
    )}
/>