reactjs onchange在一个表单中使用formik字段的值不被更新

q35jwt9p  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(156)

我是第一个做出React的人,我正在尝试对表单应用验证。
添加属性时出于某种原因:

onChange={onChange}

我想把值发送给父组件,这就是为什么我使用onchange。
我写的东西没有显示在我的文本字段中,为什么会发生这种情况?

export const Son = props => {
  const { onChange } = props;
  return (
    <Formik
      initialValues={{
        fullname: "",
        email: ""
      }}
      validationSchema={Yup.object().shape({
        fullname: Yup.string()
          .min(2, "Your name is too short")
          .required("Please enter your full name"),
        email: Yup.string()
          .email("The email is incorrect")
          .required("Please enter your email")
      })}
      onSubmit={(values, { setSubmitting }) => {
        const timeOut = setTimeout(() => {
          console.log(values);
          setSubmitting(false);

          clearTimeout(timeOut);
        }, 1000);
      }}
    >
      {({
        values,
        errors,
        touched,
        handleSubmit,
        isSubmitting,
        validating,
        valid
      }) => {
        return (
          <Form name="contact" method="post" onSubmit={handleSubmit}>
            <label htmlFor="fullname">
              Fullname
              <Field
                type="text"
                name="fullname"
                autoComplete="name"
                placeholder="your fullname"
                onChange={onChange}
              />
            </label>
            {<ErrorMessage name="fullname">{msg => <p>{msg}</p>}</ErrorMessage>}

            {/*errors.fullname && touched.fullname && <p>{errors.fullname}</p>*/}
            <br />
            <label htmlFor="email">
              Email
              <Field
                type="email"
                name="email"
                autoComplete="email"
                placeholder="your email"
                onChange={onChange}
              />
            </label>
            <ErrorMessage name="email">{msg => <p>{msg}</p>}</ErrorMessage>
            <br />
            <button type="submit" disabled={!valid || isSubmitting}>
              {isSubmitting ? `Submiting...` : `Submit`}
            </button>
          </Form>
        );
      }}
    </Formik>
  );
};

这是我的生活代码:
https://stackblitz.com/edit/react-qotvwb?file=components/son_component.js

mnemlml8

mnemlml81#

你根本没有使用formik handleChange。
我突出显示了更改that I made in https://stackblitz.com/

你可以测试一下here

相关问题