1 回答
TA贡献1775条经验 获得超8个赞
我相信该validate
方法不是向用户显示对话框的好地方。您的用例看起来像是 formik lib 的自定义需求。
import React, { useState } from "react";
import "./styles.css";
import { useFormik } from "formik";
import Swal from "sweetalert2";
import "bootstrap/dist/css/bootstrap.min.css";
export default function App() {
const [item, setItem] = useState({
name: "",
email: ""
});
const validate = (values) => {
console.log("values: ", values);
const errors = {};
if (!values.name) {
errors.name = "Required";
}
return errors;
};
const initialValues = {
name: item.name,
email: item.email
};
const formik = useFormik({
initialValues,
enableReinitialize: true,
validate,
onSubmit: (values) => {
console.log("inside onSubmit", values);
}
});
const customSubmitHandler = (event) => {
event.preventDefault();
const touched = Object.keys(initialValues).reduce((result, item) => {
result[item] = true;
return result;
}, {});
// Touch all fields without running validations
formik.setTouched(touched, false);
formik.setSubmitting(true);
formik
.validateForm()
.then((formErrors) => {
if (Object.keys(formErrors).length > 0) {
Swal.fire({
icon: "success",
title: "Yes. . .",
text: "This one should fire if everything is working right",
footer:
"<div>Problems: " + Object.keys(formErrors).join(", ") + "</div>"
});
} else {
formik.handleSubmit(event);
}
formik.setSubmitting(false);
})
.catch((err) => {
formik.setSubmitting(false);
});
};
return (
<form id="campaignForm" onSubmit={customSubmitHandler}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input
id="name"
type="text"
onChange={formik.handleChange}
value={formik.values.name}
className="form-control"
placeholder="Enter name"
/>
{formik.errors.name ? (
<div className="text-danger">{formik.errors.name}</div>
) : null}
</div>
<div className="form-group">
<label htmlFor="name">Email</label>
<input
id="name"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
className="form-control"
placeholder="Enter email"
/>
{formik.errors.email ? (
<div className="text-danger">{formik.errors.email}</div>
) : null}
</div>
<div className="form-group">
<button className="btn btn-info" type="submit">
Submit
</button>
</div>
</form>
);
}
添加回答
举报