gpt4 book ai didi

javascript - TypeError : e. preventDefault 不是 React Hook Form 上使用 EmailJs 的函数

转载 作者:行者123 更新时间:2023-12-04 14:51:26 26 4
gpt4 key购买 nike

提交表单后出现错误:
TypeError: e.preventDefault 不是函数。
这是我的代码:

import {React} from 'react';
import emailjs from 'emailjs-com';
import {useForm} from "react-hook-form";

const NameForm = () => {
const { register, handleSubmit, formState: { errors } } = useForm();
const sendEmail = (e) => {
e.preventDefault();

emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', e.target, 'YOUR_USER_ID')
.then((result) => {
console.log(result.text);

}, (error) => {
console.log(error.text);
});
e.target.reset();
}

return (
<div>
<h1 className="text-center text-md-left mb-3">Get in Touch</h1>
<form className="contact-form" onSubmit={handleSubmit(sendEmail)}>
<div className="form-group mb-0 py-3">
<textarea className="form-control custom--fields-mod text-the-primary" id="message" rows="3" placeholder="Message *" name="message" {...register("message", { required: true })}></textarea>
{errors.message && <span className="invalid-feedback d-block">Please fill out this field.</span>}
</div>
<div className="form-group row py-2 mb-0">
<div className="col-md-6">
<div>
<div className="d-flex align-items-center">
<input className="mr-2" type="checkbox" id="yes_i_understand" name="yes_i_understand" {...register("yes_i_understand", { required: true })} />
<label className="font-size-12 mb-0" htmlFor="yes_i_understand">I understand and agree to the Privacy Policy and Terms and Conditions.</label>
</div>{errors.yes_i_understand && <span className="invalid-feedback d-block">You must agree before submitting.</span>}
</div>
</div>
<div className="col-md-6 text-center text-md-left py-2 py-md-0">
<input className="buttons-width float-md-right btn btn-dark-moderate-orange rounded-0" type="submit" value="SEND MESSAGE" />
</div>
</div>
</form>
</div>
);

}
export default NameForm;
我看到了 react 钩子(Hook)表单示例,但我不确定在将数据传递给表单时是否遗漏了一些东西。
你可以在这里查看:
https://codesandbox.io/s/react-hook-form-using-emailjs-2k6x5

最佳答案

虽然 Guillaume 的回答解决了问题,但以下解决方案将是仅使用 react-hook-form 来处理它的方法。并且不使用 event完全反对。所以只需使用 emailjs.send方法并将 RHF 提供的表单值传递给此方法。要重置表单,您可以使用 reset RHF的方法。

const {
register,
handleSubmit,
reset,
formState: { errors }
} = useForm();
const sendEmail = (formData) => {
emailjs
.send("YOUR_SERVICE_ID", "YOUR_TEMPLATE_ID", formData, "YOUR_USER_ID")
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
reset();
};
Edit React Hook Form using Emailjs (forked)

关于javascript - TypeError : e. preventDefault 不是 React Hook Form 上使用 EmailJs 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69010847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com