我使用的是react、typescript和Email JS库。我正在使用react钩子表单库和yup来验证表单。
我需要捕捉react钩子库引发的表单验证错误,只有在没有错误的情况下,才应该使用电子邮件JS发送电子邮件。
代码的相关部分是sendEmail
函数。
sendEmail
函数中的handleSubmit(onSubmit)();
验证表单。[handleSubmit的文档]https://react-hook-form.com/api/useform/handlesubmit/#main
我把handleSubmit(onSubmit)()
放在try-catch块中,但它没有捕获错误。代码继续,并发送电子邮件。如果存在表单验证错误,我如何停止发送电子邮件。
import React, { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { string, number, object, InferType } from "yup";
import { url } from "inspector";
import emailjs from "@emailjs/browser";
function onSubmit(values: Props) {}
type Props = InferType<typeof schema>;
const schema = object({
firstName: string().required("First name is required"),
lastName: string().required("Last name is required"),
});
function FormEmail() {
const form = useRef(null);
const [value, setValue] = useState<string | undefined>();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<Props>({
resolver: yupResolver(schema),
});
const sendEmail = (e: { preventDefault: () => void }) => {
e.preventDefault();
try {
handleSubmit(onSubmit)();
emailjs
.sendForm(
"service_ztay5wh",
"template_wcc4f29",
form.current!,
"aXbWTWKdwzgImlYqz"
)
.then(
(result: { text: any }) => {
console.log(result.text);
},
(error: { text: any }) => {
console.log(error.text);
}
);
} catch (e) {
return;
}
};
return (
<div>
<form onSubmit={sendEmail} ref={form}>
<h3>First Name</h3>
<input
id="firstName"
type="text"
{...register("firstName")}
/>
<span className="error">{errors?.firstName?.message}</span>
<h3>Last Name</h3>
<input
id="lastName"
type="text"
{...register("lastName")}
/>
<span className="error">{errors?.lastName?.message}</span>
<button className="" type="submit">
Submit
</button>
</form>
</div>
);
}
export default FormEmail;
非常感谢您的帮助!谢谢
我改变了以前的答案。
我需要捕捉react钩子库引发的表单验证错误,只有在没有错误的情况下,才应该使用电子邮件JS发送电子邮件。
正如我所知,react hook表单不会抛出错误,而是设置错误状态。因此,您可以使用错误状态或isValid标志来阻止在提交功能中发送电子邮件。关于你评论中的ts错误,看看这个api文档
const {
register,
handleSubmit,
formState: { errors, isValid },
} = useForm<Props>({
resolver: yupResolver(schema),
});
const sendEmail = handleSubmit((_, e) => {
e?.preventDefault();
try {
onSubmit();
if (isValid) {
// send email
}
} catch (e) {
// only catch error thrown by emailjs
return;
}
});
return (
<form onSubmit={sendEmail} ref={form}>
...
)
或
const {
register,
handleSubmit,
formState: { errors, isValid },
} = useForm<Props>({
resolver: yupResolver(schema),
});
const sendEmail = () => {
try {
onSubmit();
if (isValid) {
// send email
}
} catch (e) {
// only catch error thrown by emailjs
return;
}
};
return (
<form ref={form}>
...
<button className="" onClick={sendEmail}>
Submit
</button>
</form>
)