如何从儿童组件获得formik道具?

时间:2019-06-25 12:06:29

标签: reactjs formik

我具有Formik形式,并且需要以某种方式从内部到外部获得Formik道具(特别是serFieldError)。

我的代码:

const SignUp = props => {
  const onSubmitClick = values => {
    //...
  };

  const SignUpView = props => {
    const { setFieldError } = props;

    //..

    return (
    <Form className="signup-form"/>
    //...
    );
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={signUpSchema}
      onSubmit={onSubmitClick}
      render={SignUpView}
    />
  );
};

有什么方法可以将setFieldError(内部)传递到SignUpView(外部)?

1 个答案:

答案 0 :(得分:0)

这里是根据您的代码修改的代码。

const SignUp = props => {
  let setFieldErrorParentReference = null;

  // This method's signature is wrong, it gets an object containing 'values' property in it.
  // Here's proper signature https://jaredpalmer.com/formik/docs/api/formik#onsubmit-values-values-formikbag-formikbag-void
  const onSubmitClick = values => {
    //...
  };

  const SignUpView = props => {
    const { setFieldError } = props;
    // Every time SignUpView renders it will get new formik object and then that new object reference will be stored and you can do whatever yuo want using that.
    setFieldErrorParentReference = setFieldError;

    //..

    return (
    <Form className="signup-form"/>
    //...
    );
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={signUpSchema}
      onSubmit={onSubmitClick}
      render={SignUpView}
    />
  );
};