Not*_*sql 3 typescript reactjs
React Typescript 阻止我使用emailJS的样板代码。
我修改了样板代码以修复 UseRef() 和 const sendEmail 上的一个错误。
我在函数 sendForm() 的 form.current 行上收到错误。
错误:(属性)React.RefObject.current:HTMLFormElement | 无效的
'HTMLFormElement | 类型的参数 null' 不可分配给'string | 类型的参数 HTMLFormElement'。类型“null”不可分配给类型“string |” HTMLFormElement'.ts(2345)
import React, { useRef } from 'react';
import emailjs from '@emailjs/browser';
export const ContactUs = () => {
const form = useRef<HTMLFormElement>(null);
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_PUBLIC_KEY')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
};
return (
<form ref={form} onSubmit={sendEmail}>
<label>Name</label>
<input type="text" name="user_name" />
<label>Email</label>
<input type="email" name="user_email" />
<label>Message</label>
<textarea name="message" />
<input type="submit" value="Send" />
</form>
);
};
Run Code Online (Sandbox Code Playgroud)
这种错误就是我喜欢 TypeScript 的原因;)
编译器足够聪明,可以理解form.current可以包含表单,也可以是null,因此它的类型为HTMLFormElement | null。
在您的sendEmail函数中,您没有以任何方式考虑这种情况,因此编译器会大喊大叫,并且是完全正确的!
您必须考虑 null 的情况form.current:
const sendEmail = (e) => {
e.preventDefault();
const currentForm = form.current;
// this prevents sending emails if there is no form.
// in case currentForm cannot possibly ever be null,
// you could alert the user or throw an Error, here
if (currentForm == null) return;
// the compiler is smart enough to know that currentForm here is of type HTMLFormElement
emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', currentForm, 'YOUR_PUBLIC_KEY')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1171 次 |
| 最近记录: |