使用formik在表单中进行onchange时,字段值不会更新

时间:2019-11-20 14:57:46

标签: reactjs formik

我是新来的反应者,我正在尝试将验证应用于表单。

由于某些原因添加属性时:

onChange={onChange}

我想将值发送到父组件。这就是为什么我使用onchange。

我的文本字段中未显示任何内容,为什么会发生这种情况?

enter image description here

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

2 个答案:

答案 0 :(得分:0)

不需要onchange事件,请先删除它

enter image description here

enter image description here

答案 1 :(得分:0)

您根本没有使用格式handleChange

我突出显示了更改that I made in https://stackblitz.com/ enter image description here

,您可以测试此here正常工作