【发布时间】:2022-01-14 15:42:47
【问题描述】:
提交表单后,我想使用 useRef 清理输入。在函数handleFormSubmit 中,在发送值后我将emailRef.current.value 分配给空字符串,我有一个错误Object is possibly 'null'。为清楚起见,我不能添加可选运算符,因为赋值表达式的左侧不能是可选的。请帮忙;)
const emailRef = useRef<HTMLInputElement | null>(null);
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setEmail(emailRef.current?.value);
return onValidated({ EMAIL: email || '' }), alert('Zapisano!'), (emailRef.current.value = '');
};
<input
ref={emailRef}
type="email"
placeholder="e-mail"
className="font-medium max-w-full px-5 py-5 mr-2 rounded-md border-2 border-emerald-dark transition-all"
/>
【问题讨论】:
标签: reactjs typescript types typescript-typings