首页 > 解决方案 > 打字稿 | Typescript 在 IProps 上扩展 formikProps 时缺少 27 个 Props

问题描述

我正在将 Formik 与 TypeScript 一起使用,并且我想在 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 表单。

标签: reactjstypescripttypesreact-propsformik

解决方案


您的其他具有相同问题的问题一样,InfoFields期待您没有传入的道具:

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

            <InfoFields {...formikProps} />

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

你能告诉我如何只访问我想要的 formikProps,所以 TS 不会抱怨

而不是上面的,你可以选择你真正想要的道具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>
    )}
/>

推荐阅读