React TypeScript集成EmailJS表单时出现ref类型错误
React TypeScript 中 EmailJS 表单的 Ref 类型错误修复
问题重现
复制 EmailJS 官方文档代码后,ref={form} 处触发 TypeScript 类型错误,原代码如下:
import React, { useRef } from 'react'; import emailjs from '@emailjs/browser'; export const ContactUs = () => { const form = useRef(); const sendEmail = (e) => { e.preventDefault(); emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_PUBLIC_KEY') .then((result: { text: any }) => { console.log(result.text); }, (error: { text: any }) => { console.log(error.text); }); }; return ( <form ref={form} onSubmit={sendEmail}> <label>Name</label> <input type="text" name="user_name" /> <input type="submit" value="Send" /> </form> ); };
错误信息(翻译后)
(属性) React.ClassAttributes.ref?: React.LegacyRef
| undefined
类型“MutableRefObject”不能赋值给类型“LegacyRef | undefined”。
类型“MutableRefObject”不能赋值给类型“RefObject ”。
属性“current”的类型不兼容。
类型“undefined”不能赋值给类型“HTMLFormElement | null”。ts(2322)index.d.ts(137, 9): 预期类型来自属性“ref”,该属性在类型“DetailedHTMLProps<FormHTMLAttributes
, HTMLFormElement>”上声明。
错误原因
useRef()未指定泛型类型,默认推断为MutableRefObject<undefined>,但表单元素的 ref 要求类型为HTMLFormElement | null,类型不匹配导致报错。- 函数参数
e未指定类型,违反 TypeScript 类型检查规则。
修复方案
- 给
useRef指定泛型HTMLFormElement,并初始化current为null,明确 ref 指向表单元素。 - 为
sendEmail的参数e添加React.FormEvent<HTMLFormElement>类型。 - 调用
emailjs.sendForm前,增加form.current非空判断,避免运行时潜在错误。
修复后完整代码
import React, { useRef, FormEvent } from 'react'; import emailjs from '@emailjs/browser'; export const ContactUs = () => { // 指定泛型并初始化current为null const form = useRef<HTMLFormElement>(null); // 给e指定FormEvent类型 const sendEmail = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); // 非空判断确保类型安全 if (!form.current) return; 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" /> <input type="submit" value="Send" /> </form> ); };
内容的提问来源于stack exchange,提问作者Travis
相关产品推荐
相关产品推荐

