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

时间:2019-04-15 18:26:09

标签: reactjs typescript types react-props formik

我正在将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不会抱怨。而且我还有另一个问题。如何将道具从组件传递到Formik表单。

1 个答案:

答案 0 :(得分:1)

与具有相同问题的your other question一样,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>
    )}
/>