如何在以formik提交时禁用自动重置表单?

时间:2020-03-16 12:14:50

标签: reactjs formik

我有一个由formik控制的表单,当我填写所有字段并按按钮提交时,将调用函数onSubmit,并且我的表单将重置此值。

有时我的数据不正确(例如重复的电子邮件),我需要保留这些数据。

我该怎么做?

这是我的代码:

    const schema = Yup.object().shape({
        login: Yup.string()
            .email('Email não possui formato válido')
            .required('Informe o email!'),
        password: Yup.string().required('Informe a senha!'),
    })

    const formik = useFormik({
        initialValues: {
          login: '', password: '', inactive: false
        },

        validationSchema: schema,
        onSubmit: values => {
            registerUser(values)
        }
    })

return (
    <form onSubmit={formik.handleSubmit} className={classes.form} noValidate>
        <Grid container spacing={3}>

            <Grid item xs={12}>
                <Typography className={classes.observation} component="h6">* Necessário preenchimento do cadastro geral para liberar permissão de telas</Typography>
            </Grid>

            <Grid item xs={5}>
                <TextField
                    value={formik.values.login}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={formik.touched.login ? formik.errors.login : ""}
                    error={formik.touched.login && Boolean(formik.errors.login)}
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    id="email"
                    label="E-mail"
                    name="login"
                    autoComplete="email"
                />
            </Grid>

            <Grid item xs={5}>
                <TextField
                    value={formik.values.password}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={formik.touched.password ? formik.errors.password : ""}
                    error={formik.touched.password && Boolean(formik.errors.password)}
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    type="password"
                    id="password"
                    label="Senha"
                    name="password"
                />
            </Grid>

            <Grid item xs={2}>
                <FormControlLabel
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    value={formik.values.inactive}
                    control={<Switch color="primary" />}
                    label="Inativo"
                    labelPlacement="top"
                />
            </Grid>

            <Grid item xs={3}>
                <Button fullWidth 
                    variant="contained" 
                    color="primary"
                    type="submit"
                >
                    Cadastrar
                </Button>
            </Grid>

        </Grid>
    </form>
);

2 个答案:

答案 0 :(得分:1)

您需要更新以下行:

    <form onSubmit={(e) => { e.preventDefault(); formik.handleSubmit(e)}} className={classes.form} noValidate>

答案 1 :(得分:0)

使用formik中的Form,默认是提交时不重置:

import { Formik, Form } from "formik";

function DemoComp(){
  return(
     <Formik
        initialValues={{ fieldOneVal: "" }}
        onSubmit={async (formsData, {setSubmitting, resetForm}) => {
          setSubmitting(true)
          // async request
          // --> if wanted to reset on submit: resetForm();
          console.log(formsData)
          setSubmitting(false)
        }}
      >
        {({ values, isSubmitting, handleChange, handleBlur, handleSubmit }) => (
          <Form>
            <input
              type="text"
              name="fieldOneVal"
              value={values.fieldOneVal}
              onChange={handleChange}
              onBlur={handleBlur}
            />
            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>    

  )
}