React Formik提交

huangapple go评论55阅读模式
英文:

React Formik submission

问题

我有一个用于注册的授权和验证表单。我需要使我的表单在按钮上可点击。首先,我添加了resetform函数,以便了解我的表单实际上是如何工作的,但在每次点击后什么都不会发生。

我点击了按钮,但什么都没有发生,但它应该在此操作后重置所有输入。

英文:

I have an authorization and validation form for registration. I need to to make my form available for click events at my button. At first i added the resetform function in order to notice how my form actually works but after each click nothing happens.

import { Button, TextField } from "@mui/material";
import * as yup from "yup";
import { Formik } from "formik";

export const RegistrationForm = () => {
  const validationSchema = yup.object().shape({
    name: yup
      .string()
      .typeError("Должно быть строкой")
      .required("Обязательно")
      .matches(/^[аА-яЯ\s]+$/, "Имя должно состоять из русских букв"),
    secondName: yup
      .string()
      .typeError("Должно быть строкой")
      .required("Обязательно")
      .matches(/^[аА-яЯ\s]+$/, "Фамилия должна состоять из русских букв"),
    login: yup
      .string()
      .typeError("Должно быть строкой")
      .required("Обязательно"),
    password: yup
      .string()
      .typeError("Должно быть строкой")
      .required("Обязательно"),
    confirmPassword: yup
      .string()
      .oneOf([yup.ref("password")], "Пароли не совпадают")
      .required("Обязательно"),
    email: yup.string().email("Введите верный email").required("Обязательно"),
    confirmEmail: yup
      .string()
      .email("Введите верный email")
      .oneOf([yup.ref("email")], "Email не совпадают")
      .required("Обязательно"),
  });

  return (
    <>
      <header>
        <div className="head-btns">
          <Button variant="outlined">Зарегистрироваться</Button>
          <Button variant="outlined">Авторизоваться</Button>
        </div>
      </header>
      <Formik
        initialValues={{
          name: "",
          secondName: "",
          login: "",
          password: "",
          confirmPassword: "",
          email: "",
          confirmEmail: "",
        }}
        validateOnBlur
        onSubmit={({ resetForm }) => resetForm()}
        validationSchema={validationSchema}
      >
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isValid,
          dirty,
        }) => (
          <div className="register">
            <TextField
              id="outlined-basic"
              label="Имя"
              variant="outlined"
              className="field"
              name={"name"}
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.name}
            />
            {touched.name && errors.name && (
              <p className={"error"}>{errors.name}</p>
            )}
            <TextField
              id="outlined-basic"
              label="Фамилия"
              variant="outlined"
              className="field"
              name={"secondName"}
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.secondName}
            />
            {touched.secondName && errors.secondName && (
              <p className={"error"}>{errors.secondName}</p>
            )}
            <TextField
              id="outlined-basic"
              label="Логин"
              variant="outlined"
              className="field"
              name={"login"}
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.login}
            />
            {touched.login && errors.login && (
              <p className={"error"}>{errors.login}</p>
            )}
            <TextField
              type="password"
              id="outlined-basic"
              label="Пароль"
              variant="outlined"
              className="field"
              name={"password"}
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.password}
            />
            {touched.password && errors.password && (
              <p className={"error"}>{errors.password}</p>
            )}
            <TextField
              type="password"
              id="outlined-basic"
              label="Подтвердите пароль"
              variant="outlined"
              className="field"
              name={"confirmPassword"}
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.confirmPassword}
            />
            {touched.confirmPassword && errors.confirmPassword && (
              <p className={"error"}>{errors.confirmPassword}</p>
            )}
            <TextField
              id="outlined-basic"
              label="Email"
              variant="outlined"
              className="field"
              name={"email"}
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.email}
            />
            {touched.email && errors.email && (
              <p className={"error"}>{errors.email}</p>
            )}
            <TextField
              id="outlined-basic"
              label="Подтвердите Email"
              variant="outlined"
              className="field"
              name={"confirmEmail"}
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.confirmEmail}
            />
            {touched.confirmEmail && errors.confirmEmail && (
              <p className={"error"}>{errors.confirmEmail}</p>
            )}
            <Button
              onClick={handleSubmit}
              disabled={!isValid || !dirty}
              type="submit"
              variant="contained"
              className="btn"
            >
              Зарегистрироваться
            </Button>
          </div>
        )}
      </Formik>
    </>
  );
}; 

I clicked the button and nothing happens but it should reset all inputs after this action

答案1

得分: 0

onSubmit属性传递给<Formik />组件应该是这样的:

  <Formik
    onSubmit={(values, { resetForm }) => resetForm()}
    validationSchema={validationSchema}
  >
  </Formik>

Formik选项被传递给提交处理程序的第二个参数。

如果您在HTML form标签中定义表单,就不需要为按钮显式指定onClick处理程序,并且不需要使用type="submit"

  <Formik
    onSubmit={(values, { resetForm }) => resetForm()}
    validationSchema={validationSchema}
  >
    {({ handleSubmit }) => (
        <form onSubmit={handleSubmit}>
          {/* 您的表单 */}
          <Button 
            type="submit" // 在form中的按钮指定type为submit会自动调用handleSubmit方法
          >
           提交
          </Button>
        </form>

    )}
  </Formik>
英文:

The onSubmit prop given to the &lt;Formik /&gt; component should be like this:

  &lt;Formik
    onSubmit={(values, { resetForm }) =&gt; resetForm()}
    validationSchema={validationSchema}
  &gt;
  &lt;/Formik&gt;

Formik options are passed to the second parameter of the submit handler.

And you don't need to explicitly give your Button onClick handler with type=&quot;submit&quot; if you define your form in the HTML form tag.

  &lt;Formik
    onSubmit={(values, { resetForm }) =&gt; resetForm()}
    validationSchema={validationSchema}
  &gt;
    {({ handleSubmit }) =&gt; (
        &lt;form onSubmit={handleSubmit&gt;
          {/* your form */}
          &lt;Button 
            type=&quot;submit&quot; // giving type submit to a button enclosed in a form will automatically call handleSubmit method
          &gt;
           Submit
          &lt;/Button&gt;
        &lt;/form&gt;

    )}
  &lt;/Formik&gt;

huangapple
  • 本文由 发表于 2023年2月10日 14:40:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定