首页 > 解决方案 > Typescript/React useRef 错误:(属性)React.RefObject.current: HTMLFormElement | 空对象可能是“空”.ts(2531)

问题描述

我遇到了 Typescript 的问题,它给了我下面列出的以下错误。的部分const formRef = useRef<HTMLFormElement>(null);似乎很好,但问题似乎与formRef.current.checkValidity().

如何添加打字稿打字/摆脱错误?

错误:

(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');
    }
  };

标签: reactjstypescripttypestypescript-typings

解决方案


正如错误所说,问题在于 ref 可能是null - 事实上,这就是您将其初始化的内容。那意味着formRef.current可能null。这意味着formRef.current.checkValidity()需要检查是否formRef.currentnull.

您可以使用&&

if (formRef.current && formRef.current.checkValidity()) {
//  ^^^^^^^^^^^^^^^^^^^

或新的可选链接运算符

if (formRef.current?.checkValidity()) {
//                 ^

旁注:几乎没有任何理由=== trueor === false,当然也没有。checkValidity返回一个布尔值,所以你已经有一个布尔值可以用if.

// Idiomatically:
if (x) {  // Is this true?
    // ...
}

if (!x) { // Is this false?
    // ...
}

¹“几乎” - 唯一真正有意义的是,如果您正在测试的内容可能根本不是布尔值,并且您希望检查结果false是否不是,这是一种罕见的边缘情况。


推荐阅读