如何解决Typescript / React useRef错误:属性React.RefObject <HTMLFormElement> .current:HTMLFormElement | null对象可能是'null'.ts2531
我在打字稿方面遇到问题,这给我下面列出的以下错误。 const formRef = useRef<HTMLFormElement>(null);
的部分似乎不错,但问题似乎出在formRef.current.checkValidity()
上。
如何添加Typescript键入/消除错误?
错误:
(property) React.RefObject<HTMLFormElement>.current: HTMLFormElement | null
Object is possibly 'null'.ts(2531)
代码:
// React Hooks: Refs
const formRef = useRef<HTMLFormElement>(null);
// Send Verification Code
const sendVerificationCode = (event: any) => {
// Event: Cancels Event (Stops HTML Default Form Submit)
event.preventDefault();
// Event: Prevents Event Bubbling To Parent Elements
event.stopPropagation();
// const reference = <HTMLFormElement>formRef.current;
console.log('WHY IS THE FORM VALID???');
console.log(formRef.current.checkValidity());
// Check Form Validity
if (formRef.current.checkValidity() === true) {
// Validate Form
setValidated(true);
// Redux: Send Verification Code Request
dispatch(sendVerificationCodeRequest(email));
}
else {
// Do Nothing (Form.Control.Feedback Will Appear)
console.log('DO NOTHING');
}
};
解决方法
正如错误所言,问题在于ref可能是null
-实际上,这就是初始化它的目的。这意味着formRef.current
可能是null
。这意味着formRef.current.checkValidity()
需要检查formRef.current
是否为null
。
您可以使用&&
:
if (formRef.current && formRef.current.checkValidity()) {
// ^^^^^^^^^^^^^^^^^^^
或新的optional chaining operator:
if (formRef.current?.checkValidity()) {
// ^
旁注:几乎没有任何理由=== true
或=== false
,当然也没有上述理由。 checkValidity
返回一个布尔值,因此您已经已经使用if
进行测试的布尔值。
// Idiomatically:
if (x) { // Is this true?
// ...
}
if (!x) { // Is this false?
// ...
}
¹“几乎”-唯一真正有意义的是,您要测试的内容可能根本不是布尔值,并且您希望检查结果为false
,如果不是,则为罕见的情况。
您必须以某种方式确保formRef.current
不是null
,因为它可能是。一种方法是将其添加到回调的开头:
if(!formRef.current) return
您也可以使用可选的链接运算符,尽管在这种情况下,如果formRef.current
最终为null
,则会触发代码的DO NOTHING
部分
if(formRef.current?.checkValidity() === true)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。