一旦单击“下一步”按钮,我将在反应中使用多步骤表单,但是它现在也要验证表单,因此,一旦完成验证,就需要重定向到下一步。
这是我的代码:

import React, { useState } from 'react';
import SimpleReactValidator from 'simple-react-validator';

const UserDetails = ({ setForm, formData, navigation }) => {
     const {
    fullName
    } = formData;
    const useForceUpdate = () => useState()[1];
    const validator = new SimpleReactValidator();

    const forceUpdate = useForceUpdate();
    const submitForm = (e) =>{
        e.preventDefault()

        if (validator.allValid()) {
          alert('You submitted the form and stuff!');
        } else {

            validator.showMessages();
           forceUpdate();
        }
      }
      {validator.showMessages('fullName', fullName, 'required|alpha')}
      {validator.showMessages('fullName', fullName, 'required|alpha')}
return(
<>
<input
type="text"
name="fullName"
placeholder='Name'
onChange={setForm}
defaultValue={fullName} />
    <label className="form__label" htmlFor ="fullname">Name</label>
  {validator.message('fullName', fullName, 'required|alpha')}
 <button className="btn green_btn w250 font22"  onClick={submitForm}>
Next </button>
</>


我想要所有数据验证之后

    const { next } = navigation;


此代码应启用,然后转到下一步。

最佳答案

使用react-router的useHistory钩子。完成所有验证后,将下一页的路径名添加到它。

import React, { useState } from 'react';
import SimpleReactValidator from 'simple-react-validator';
import { useHistory } from 'react-router-dom';

const UserDetails = ({ setForm, formData, navigation }) => {
     const {
    fullName
    } = formData;
    const useForceUpdate = () => useState()[1];
    const validator = new SimpleReactValidator();
    const history=useHistory()
    const forceUpdate = useForceUpdate();
    const submitForm = (e) =>{
        e.preventDefault()

        if (validator.allValid()) {
          history.push('/pathname for nextpage')
          alert('You submitted the form and stuff!');
        } else {

            validator.showMessages();
           forceUpdate();
        }
      }
      {validator.showMessages('fullName', fullName, 'required|alpha')}
      {validator.showMessages('fullName', fullName, 'required|alpha')}
return(
<>
<input
type="text"
name="fullName"
placeholder='Name'
onChange={setForm}
defaultValue={fullName} />
    <label className="form__label" htmlFor ="fullname">Name</label>
  {validator.message('fullName', fullName, 'required|alpha')}
 <button className="btn green_btn w250 font22"  onClick={submitForm}>
Next </button>
</>

08-08 07:02
查看更多