我想让我用Formik和Yup创建的表单给我发一封电子邮件"onSubmit"但我不确定我需要在我的"onsubmit"中添加什么。让它工作的函数。或者我是否需要handlessubmit如果需要,我是否需要写出来,让它给我发邮件?
function Contact(){
return (
<Formik
initialValues={{
name: '',
email: '',
message: '',
}}
validationSchema={Yup.object({
name: Yup.string()
.required('Required'),
email: Yup.string()
.email('Invalid Email Address')
.required('Required'),
message: Yup.string()
.min(7, 'More details are always helpful.')
.required('Required')
})}
onSubmit={(values, { setSubmitting, resetForm }) => {
setTimeout(() => {
resetForm();
setSubmitting(false);
}, 3000)
}}
>
{props => (
<Form>
<h4>Shoot me a message here.</h4>
<div className="field half first">
<CustomTextInput label="Name" name="name" type="text" placeholder="Enter Name" />
</div>
<div className="field half">
<CustomTextInput label="Email" name="email" type="email" placeholder="Enter Your Email" />
</div>
<div className="field">
<CustomTextarea label="message" name="message" rows="4" placeholder="Your Message Here" />
</div>
<button type="submit" className="special">{props.isSubmitting ? 'Sending...' : 'Send Message'}</button>
</Form>
)}
</Formik>
我认为这是你应该采取的方法:
function Contact() {
const sendDataToEmailApi = (values) => {
// call your email api with the values
return true; // to show the send process was successful
};
const handleSubmit = (values, { setSubmitting, resetForm }) => {
const emailWasSent = sendDataToEmailApi(values);
if (emailWasSent) {
resetForm();
setSubmitting(false);
}
};
const validationSchema = Yup.object({
name: Yup.string().required("Required"),
email: Yup.string().email("Invalid Email Address").required("Required"),
message: Yup.string()
.min(7, "More details are always helpful.")
.required("Required"),
});
return (
<Formik
initialValues={{
name: "",
email: "",
message: "",
}}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
{/* ... */}
</Formik>
);
}