react | 如何向上传递 FormikProps 一个组件

IT技术 javascript reactjs typescript react-props formik
2021-05-23 10:06:17

我正在尝试通过,values并且props该 formik 需要 1 个组件。我正在为某些表单使用各种小组件,并且我将它们传递到一个复杂的组件中,该组件需要在调用时将它们传递给每个单独的渲染。

基本上所有的 FormikProps。这是一个这样的组件。

import React, { Fragment } from 'react';
import debounce from 'debounce-promise';
import classNames from 'classnames';
import { Field, FormikProps, ErrorMessage } from 'formik';

import Asterisk from 'shared/common/components/element/Asterisk';
import { validateUsername } from '../../utils/index';

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

export const InfoFields = (props: FormikProps<IValues>): JSX.Element => {
  const debounceUsernameValidation = (): void => {
    debounce(validateUsername, 500);
  };

  const { touched, errors } = props;

  return (
    <Fragment>
      <div className="pb-2">
        <label className="font-weight-bold" htmlFor="username">
          Username <Asterisk />
        </label>
        <Field
          validate={debounceUsernameValidation}
          className={classNames('form-control', {
            'is-invalid': errors.username && touched.username
          })}
          placeholder="Username (Required)"
          autoComplete="username"
          name="username"
          type="text"
        />
        <ErrorMessage name="username" component="div" className="text-danger" />
      </div>
      <div className="py-2">
        <label className="font-weight-bold">Email</label>
        <Field
          className={classNames('form-control', {
            'is-invalid': errors.email && touched.email
          })}
          autoComplete="email"
          placeholder="Email"
          name="email"
          type="email"
        />
        <ErrorMessage name="email" component="div" className="text-danger" />
      </div>
    </Fragment>
  );
};

export default InfoFields;

在这里,我在复杂组件中调用它:



  render(): ReactNode {
    const { mode } = this.props;
    return (
      <Formik
        initialValues={this.getInitialValues()}
        validationSchema={this.getValidationSchemas()}
        onSubmit={this.handleSubmit}
        validateOnBlur={false}
        render={({ status, isSubmitting }) =>
          (
            <Form>
              {status && (
                <div className="mb-3 text-danger" data-test="user-form-error-message">
                  {status}
                </div>
              )}
              {mode === ActionMode.ADD_USER && (
                <Fragment>
                  <InfoFields /> // This is the component from above
                </Fragment>
              )}
              <Button
                className="btn btn-primary w-100 mt-5"
                disabled={isSubmitting}
                loading={isSubmitting}
                type="submit"
              >
                {mode === ActionMode.ADD_USER && <span>CREATE USER</span>}
              </Button>
            </Form>
          ) as ReactNode
        }
      />
    );
  }

现在,当我在另一个组件中调用该组件时,出现此错误:

Uncaught TypeError: Cannot read property 'username' of undefined. It refers to this line of code:
errors.username && touched.username and this
errors.email && touched.email
interface IProps {
  doSubmit(service: object, values: object): LensesHttpResponse<string>;
  onSave(values: { username?: string; email?: string; password?: string; group?: string }): void;
  notify(config: object): void;
  mode: ActionMode;
  user: IUser;
}

interface IValues extends FormikValues {
  username?: string;
  email?: string;
  password?: string;
  group?: string;
}

我需要一种方法将propsusername, email和其余部分传递给每个单独的组件。问题是该组件被称为 2 次渲染,因此它无法访问它们

我在这里不知所措。有人能帮我吗?谢谢!!

1个回答

InfoFields尽管您已将该组件编写为 accept 但您实际上并未将 props 传递FormikProps<IValues>您可以像这样传递 Formik 的props:

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

            <InfoFields {...formikProps} />

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

或者(我个人的喜好),删除InfoField的props并Field用作渲染props,例如:

<Field
    name="username"
    validate={debounceUsernameValidation}
>
    {({ field, form }: FieldProps) => (
        <Fragment>
            <input
                {...field}
                className={classNames('form-control', {
                    'is-invalid': form.errors[field.name] &&
                        form.touched[field.name]
                })}
                placeholder="Username (Required)"
                type="text"
            />
            <ErrorMessage 
                name={field.name} 
                component="div" 
                className="text-danger" 
            />
        </Fragment>
    )}
</Field>

使用 field 渲染props,您可以访问嵌套在更下方的组件中的表单值,而无需到处传递props。