提交反应表格未提交的按钮

发布于 2025-02-13 05:13:28 字数 5942 浏览 1 评论 0原文

我正在尝试使用React.js和Formik制作注册表格。我的提交按钮可以正确显示,但是当我尝试通过单击“提交”按钮提交信息时,什么也不会发生。请告知我如何解决此问题。提前致谢。

registrationform.js:

import React from 'react';
import { Formik, Form } from 'formik';
import * as yup from 'yup';
import FormikControl from './FormikControl';
import classes from './Registration.module.css';

function Registrationform() {
  const options = [
    { key: 'Email', value: 'emailmoc' },
    { key: 'Telephone', vlaue: 'telephonemoc' }
  ];

  const initialValues = {
    email: '',
    password: '',
    confirmPassword: '',
    modeOfContact: '',
    phone: ''
  };

  const validationSchema = yup.object({
    email: yup.string().email('Invalid email format').required('Required'),
    password: yup.string().required('Required'),
    confirmPassword: yup
      .string()
      .oneOf([yup.ref('password'), ''], 'Passwords must match')
      .required('required'),
    modeOfContact: yup.string().required('Required'),
    phone: yup.string().when('modeOfContact', {
      is: 'telephonemoc',
      then: yup.string().required('Required')
    })
  });

  const onSubmit = (values) => {
    console.log('Form data', values);
  };

  return (
    <div>
      <h1>Registration</h1>

      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={onSubmit}
      >
        {(formik) => {
          return (
            <Form className={classes.Registrationform}>
              <FormikControl
                control="input"
                type="email"
                label="Email"
                name="email"
              />

              <FormikControl
                control="input"
                type="password"
                label="Password"
                name="password"
              />

              <FormikControl
                control="input"
                type="password"
                label="Confirm Password"
                name="confirmPassword"
              />

              <FormikControl
                control="input"
                type="text"
                label="Phone number"
                name="phone"
              />

              <label>Mode of Contact</label>

              <div className="radio">
                <label>
                  <input type="radio" value="Phone" options={options} />
                  Phone
                </label>
              </div>
              <div className="radio">
                <label>
                  <input type="radio" value="Email" options={options} />
                  Email
                </label>
              </div>
              <button type="submit" disabled={!formik.isValid}>
                Submit
              </button>
            </Form>
          );
        }}
      </Formik>
    </div>
  );
}

export default Registrationform;

registration.module.css:

  .Registrationform{
        margin:auto;
        padding-top: 50px;
        width:360px;
         
    }
    
    .Registrationform > label {
     
        font-weight: bold;
        display: flex;
        margin-bottom: 10px;
       
        font-size: 18px;
      }
      
      .Registrationform > input  {
       margin-bottom: 10px;
        font-weight: bold;
        display: inline-flex;
        margin-right: 20px;
        border-radius: 6px;
        outline:none;
        border: none;
        border: 1px solid #1E90FF;
       
      }
    
    
      .Registrationform > button{
        margin-top: 10px;
        width: 425px;
        height: 35px;
        border-radius: 6px;
        outline:none;
        border: none;
        border: 1px solid #1E90FF;
        background-color: #1E90FF;
        color: white;
        font-size: 18px;
    
      }
    
      h1{
        margin-top: 50px;
        margin-bottom: 0;
        padding-bottom: 0;
      }

formikcontainer:

import React from 'react';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';
import FormikControl from './FormikControl';

function FormikContainer() {
  const initialValues = {
    email: '',
    password: ''
  };
  const validationschema = Yup.object({
    email: Yup.string().required('Required')
  });
  const onSubmit = (values) => console.log('Form data', values);

  return (
    <div>
      <Formik
        initialValues={initialValues}
        validationschema={validationschema}
        onSubmit={onSubmit}
      >
        {(formik) => (
          <Form>
            <FormikControl
              control="input"
              type="email"
              label="Email"
              name="email"
            />

            <FormikControl
              control="input"
              type="password"
              label="Password"
              name="password"
            />

            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

export default FormikContainer;

formikcontrol:

import React from 'react';

function FormikControl({ control, id, label, ...rest }) {
  return (
    <>
      {control === 'input' && <label htmlFor={id}>{label}</label>}
      <input id={id} {...rest} />
    </>
  );
}

export default FormikControl;

app.js:

import React from 'react';
import './App.css';
import FormikContainer from './components/FormikContainer';
import LoginForm from './components/LoginForm';
import Registrationform from './components/RegistrationForm';

function App() {
  return (
    <div>
      <LoginForm />
      <Registrationform />
    </div>
  );
}

export default App;

I am trying to make a registration form using React.js and Formik. My submit button displays correctly but when I try to submit the information by clicking on the submit button nothing happens. Please advise how I can fix this. Thanks in advance.

RegistrationForm.js:

import React from 'react';
import { Formik, Form } from 'formik';
import * as yup from 'yup';
import FormikControl from './FormikControl';
import classes from './Registration.module.css';

function Registrationform() {
  const options = [
    { key: 'Email', value: 'emailmoc' },
    { key: 'Telephone', vlaue: 'telephonemoc' }
  ];

  const initialValues = {
    email: '',
    password: '',
    confirmPassword: '',
    modeOfContact: '',
    phone: ''
  };

  const validationSchema = yup.object({
    email: yup.string().email('Invalid email format').required('Required'),
    password: yup.string().required('Required'),
    confirmPassword: yup
      .string()
      .oneOf([yup.ref('password'), ''], 'Passwords must match')
      .required('required'),
    modeOfContact: yup.string().required('Required'),
    phone: yup.string().when('modeOfContact', {
      is: 'telephonemoc',
      then: yup.string().required('Required')
    })
  });

  const onSubmit = (values) => {
    console.log('Form data', values);
  };

  return (
    <div>
      <h1>Registration</h1>

      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={onSubmit}
      >
        {(formik) => {
          return (
            <Form className={classes.Registrationform}>
              <FormikControl
                control="input"
                type="email"
                label="Email"
                name="email"
              />

              <FormikControl
                control="input"
                type="password"
                label="Password"
                name="password"
              />

              <FormikControl
                control="input"
                type="password"
                label="Confirm Password"
                name="confirmPassword"
              />

              <FormikControl
                control="input"
                type="text"
                label="Phone number"
                name="phone"
              />

              <label>Mode of Contact</label>

              <div className="radio">
                <label>
                  <input type="radio" value="Phone" options={options} />
                  Phone
                </label>
              </div>
              <div className="radio">
                <label>
                  <input type="radio" value="Email" options={options} />
                  Email
                </label>
              </div>
              <button type="submit" disabled={!formik.isValid}>
                Submit
              </button>
            </Form>
          );
        }}
      </Formik>
    </div>
  );
}

export default Registrationform;

Registration.module.css:

  .Registrationform{
        margin:auto;
        padding-top: 50px;
        width:360px;
         
    }
    
    .Registrationform > label {
     
        font-weight: bold;
        display: flex;
        margin-bottom: 10px;
       
        font-size: 18px;
      }
      
      .Registrationform > input  {
       margin-bottom: 10px;
        font-weight: bold;
        display: inline-flex;
        margin-right: 20px;
        border-radius: 6px;
        outline:none;
        border: none;
        border: 1px solid #1E90FF;
       
      }
    
    
      .Registrationform > button{
        margin-top: 10px;
        width: 425px;
        height: 35px;
        border-radius: 6px;
        outline:none;
        border: none;
        border: 1px solid #1E90FF;
        background-color: #1E90FF;
        color: white;
        font-size: 18px;
    
      }
    
      h1{
        margin-top: 50px;
        margin-bottom: 0;
        padding-bottom: 0;
      }

FormikContainer:

import React from 'react';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';
import FormikControl from './FormikControl';

function FormikContainer() {
  const initialValues = {
    email: '',
    password: ''
  };
  const validationschema = Yup.object({
    email: Yup.string().required('Required')
  });
  const onSubmit = (values) => console.log('Form data', values);

  return (
    <div>
      <Formik
        initialValues={initialValues}
        validationschema={validationschema}
        onSubmit={onSubmit}
      >
        {(formik) => (
          <Form>
            <FormikControl
              control="input"
              type="email"
              label="Email"
              name="email"
            />

            <FormikControl
              control="input"
              type="password"
              label="Password"
              name="password"
            />

            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

export default FormikContainer;

FormikControl:

import React from 'react';

function FormikControl({ control, id, label, ...rest }) {
  return (
    <>
      {control === 'input' && <label htmlFor={id}>{label}</label>}
      <input id={id} {...rest} />
    </>
  );
}

export default FormikControl;

App.js:

import React from 'react';
import './App.css';
import FormikContainer from './components/FormikContainer';
import LoginForm from './components/LoginForm';
import Registrationform from './components/RegistrationForm';

function App() {
  return (
    <div>
      <LoginForm />
      <Registrationform />
    </div>
  );
}

export default App;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

国产ˉ祖宗 2025-02-20 05:13:29

您需要将Formik的handlesubmit函数绑定到form> form onsubmit event侦听器。

将OnSubmit Prop添加到下面的form

   <Form onSubmit={formik.handleSubmit}>

,或将按钮代码更改为(formik doc中未提及此方法),

    <button disabled={!formik.isValid} onClick={formik.handleSubmit}>
                Submit
    </button>

此处更多地在 form api and handleseubmit

href =“ https://formik.org/docs/api/formik#handlesubmit-e-reactformeventhtmlformelement-- void @Malik-Hassam的答案:

您缺少验证模式中的密码字段。

  const validationschema = Yup.object({
    email: Yup.string().required('Required'),
    password: Yup.string(),
  });

You need to bind the handleSubmit function of formik to Form onSubmit event listener.

add the onSubmit prop to the Form as below

   <Form onSubmit={formik.handleSubmit}>

Or change your button code to (This approach is not mentioned in the formik doc)

    <button disabled={!formik.isValid} onClick={formik.handleSubmit}>
                Submit
    </button>

Here is more on Form API and handleSubmit

Update

With respect to the @malik-hassam's answer:

You are missing the password field in validation schema.

  const validationschema = Yup.object({
    email: Yup.string().required('Required'),
    password: Yup.string(),
  });
放血 2025-02-20 05:13:29

没有密码验证。

    const LoginSchema = Yup.object().shape({
    email: Yup.string()
      .email("Email must be a valid email address")
      .required("Email is required"),
    password: Yup.string().required("Password is required"),
  });

尝试使用此。

There is missing password validation.

    const LoginSchema = Yup.object().shape({
    email: Yup.string()
      .email("Email must be a valid email address")
      .required("Email is required"),
    password: Yup.string().required("Password is required"),
  });

try use this.

掩于岁月 2025-02-20 05:13:29

请在此处找到您的代码工作演示与登录组件一样

import React from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";

function Registrationform() {
  const initialValues = {
    email: "",
    password: "",
    confirmPassword: "",
    modeOfContact: "email",
    phone: ""
  };

  const validationSchema = Yup.object({
    email: Yup.string().email("Invalid email format").required("Required"),
    password: Yup.string().required("Password is required"),
    confirmPassword: Yup.string().oneOf(
      [Yup.ref("password"), null],
      "Passwords must match"
    ),
    modeOfContact: Yup.string().required("Required"),
    phone: Yup.string().matches(/^[6-9]\d{9}$/, {
      message: "Please enter valid number."
    })
  });

  const onSubmit = (values) => {
    console.log("Form data", values);
  };

  function FormikControl({ control, id, label, ...rest }) {
    return (
      <>
        {control === "input" && <label htmlFor={id}>{label}</label>}
        <input id={id} {...rest} />
      </>
    );
  }

  return (
    <div>
      <h1>Registration</h1>

      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={onSubmit}
      >
        {({
          handleChange,
          errors,
          touched,
          handleBlur,
          values,
          isValid,
          dirty
        }) => (
          <Form className="Registrationform">
            <FormikControl
              control="input"
              type="email"
              label="Email"
              name="email"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.email}
            />
            {errors.email && touched.email && errors.email}
            <FormikControl
              control="input"
              type="password"
              label="Password"
              name="password"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.password}
            />
            {errors.password && touched.password && errors.password}
            <FormikControl
              control="input"
              type="password"
              label="Confirm Password"
              name="confirmPassword"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.confirmPassword}
            />
            {errors.confirmPassword &&
              touched.confirmPassword &&
              errors.confirmPassword}
            <FormikControl
              control="input"
              type="text"
              label="Phone number"
              name="phone"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.phone}
            />
            {errors.phone && touched.phone && errors.phone}

            <label>Mode of Contact</label>

            <div className="custom-control">
              <input
                id="email"
                type="radio"
                value="email"
                name="modeOfContact"
                onChange={handleChange}
                defaultChecked={values.modeOfContact === "email"}
              />
              <label className="custom-control-label" htmlFor="email">
                email
              </label>
            </div>
            <div className="custom-control">
              <input
                id="phone"
                type="radio"
                value="phone"
                name="modeOfContact"
                onChange={handleChange}
                defaultChecked={values.modeOfContact === "phone"}
              />
              <label className="custom-control-label" htmlFor="phone">
                phone
              </label>
            </div>
            <button type="submit" disabled={!(isValid && dirty)}>
              Submit
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

export default Registrationform;


Pls find your code working demo here link and same as you can do for login component

import React from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";

function Registrationform() {
  const initialValues = {
    email: "",
    password: "",
    confirmPassword: "",
    modeOfContact: "email",
    phone: ""
  };

  const validationSchema = Yup.object({
    email: Yup.string().email("Invalid email format").required("Required"),
    password: Yup.string().required("Password is required"),
    confirmPassword: Yup.string().oneOf(
      [Yup.ref("password"), null],
      "Passwords must match"
    ),
    modeOfContact: Yup.string().required("Required"),
    phone: Yup.string().matches(/^[6-9]\d{9}$/, {
      message: "Please enter valid number."
    })
  });

  const onSubmit = (values) => {
    console.log("Form data", values);
  };

  function FormikControl({ control, id, label, ...rest }) {
    return (
      <>
        {control === "input" && <label htmlFor={id}>{label}</label>}
        <input id={id} {...rest} />
      </>
    );
  }

  return (
    <div>
      <h1>Registration</h1>

      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={onSubmit}
      >
        {({
          handleChange,
          errors,
          touched,
          handleBlur,
          values,
          isValid,
          dirty
        }) => (
          <Form className="Registrationform">
            <FormikControl
              control="input"
              type="email"
              label="Email"
              name="email"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.email}
            />
            {errors.email && touched.email && errors.email}
            <FormikControl
              control="input"
              type="password"
              label="Password"
              name="password"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.password}
            />
            {errors.password && touched.password && errors.password}
            <FormikControl
              control="input"
              type="password"
              label="Confirm Password"
              name="confirmPassword"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.confirmPassword}
            />
            {errors.confirmPassword &&
              touched.confirmPassword &&
              errors.confirmPassword}
            <FormikControl
              control="input"
              type="text"
              label="Phone number"
              name="phone"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.phone}
            />
            {errors.phone && touched.phone && errors.phone}

            <label>Mode of Contact</label>

            <div className="custom-control">
              <input
                id="email"
                type="radio"
                value="email"
                name="modeOfContact"
                onChange={handleChange}
                defaultChecked={values.modeOfContact === "email"}
              />
              <label className="custom-control-label" htmlFor="email">
                email
              </label>
            </div>
            <div className="custom-control">
              <input
                id="phone"
                type="radio"
                value="phone"
                name="modeOfContact"
                onChange={handleChange}
                defaultChecked={values.modeOfContact === "phone"}
              />
              <label className="custom-control-label" htmlFor="phone">
                phone
              </label>
            </div>
            <button type="submit" disabled={!(isValid && dirty)}>
              Submit
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

export default Registrationform;


‘画卷フ 2025-02-20 05:13:29

是的,让我添加一个代码示例。您可以使用此。

import React from "react";
import { Formik } from "formik";
import * as Emailvalidator from "email-validator";
import * as Yup from "yup";
const ValidatedLoginForm = () => (
  <>
    <Formik
      initialValues={{ email: "", password: "" }}
      onSubmit={(values, { setSubmitting }) => {
        console.log(values);
        console;
      }}
      validationSchema={Yup.object().shape({
        email: Yup.string()
          .email()
          .required("Email Required"),
        password: Yup.string()
          .required("Password Required")
          .min(8, "Password is Too short")
          .matches(/(?=.*[0-9])/, "Must Contain Number")
      })}
    >
      {props => {
        const {
          values,
          touched,
          errors,
          isSubmitting,
          handleChange,
          handleBlur,
          handleSubmit
        } = props;
        return (
          <>
            <form onSubmit={handleSubmit}>
              <label htmlFor="email">Email</label>
              <input
                name="email"
                type="text"
                placeholder="Enter your email"
                value={values.email}
                onChange={handleChange}
                onBlur={handleBlur}
                className={errors.email && touched.email && "error"}
              />
              {errors.email && touched.email && (
                <div className="input feedback">{errors.email}</div>
              )}
              <label htmlFor="email">Password</label>
              <input
                name="password"
                type="password"
                placeholder="Enter your password"
                value={values.password}
                onChange={handleChange}
                onBlur={handleBlur}
                className={errors.password && touched.password && "error"}
              />
              {errors.password && touched.password && (
                <div className="input feedback">{errors.password}</div>
              )}
              <button type="submit" disabled={isSubmitting}>
                Login
              </button>
            </form>
          </>
        );
      }}
    </Formik>
  </>
);

export default ValidatedLoginForm;

Yes let me add an example of code. you can use this.

enter link description here

import React from "react";
import { Formik } from "formik";
import * as Emailvalidator from "email-validator";
import * as Yup from "yup";
const ValidatedLoginForm = () => (
  <>
    <Formik
      initialValues={{ email: "", password: "" }}
      onSubmit={(values, { setSubmitting }) => {
        console.log(values);
        console;
      }}
      validationSchema={Yup.object().shape({
        email: Yup.string()
          .email()
          .required("Email Required"),
        password: Yup.string()
          .required("Password Required")
          .min(8, "Password is Too short")
          .matches(/(?=.*[0-9])/, "Must Contain Number")
      })}
    >
      {props => {
        const {
          values,
          touched,
          errors,
          isSubmitting,
          handleChange,
          handleBlur,
          handleSubmit
        } = props;
        return (
          <>
            <form onSubmit={handleSubmit}>
              <label htmlFor="email">Email</label>
              <input
                name="email"
                type="text"
                placeholder="Enter your email"
                value={values.email}
                onChange={handleChange}
                onBlur={handleBlur}
                className={errors.email && touched.email && "error"}
              />
              {errors.email && touched.email && (
                <div className="input feedback">{errors.email}</div>
              )}
              <label htmlFor="email">Password</label>
              <input
                name="password"
                type="password"
                placeholder="Enter your password"
                value={values.password}
                onChange={handleChange}
                onBlur={handleBlur}
                className={errors.password && touched.password && "error"}
              />
              {errors.password && touched.password && (
                <div className="input feedback">{errors.password}</div>
              )}
              <button type="submit" disabled={isSubmitting}>
                Login
              </button>
            </form>
          </>
        );
      }}
    </Formik>
  </>
);

export default ValidatedLoginForm;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文