【问题标题】:TypeScript : Object is possibly 'null' useRefTypeScript:对象可能是“空”useRef
【发布时间】: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


    【解决方案1】:

    添加 if 语句,

    const emailRef = useRef<HTMLInputElement | null>(null);
    
    const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
    
        setEmail(emailRef.current?.value);
    
        if (emailRef.current) {
          emailRef.current.value = ''
        }
    
    
        return onValidated({ EMAIL: email || '' }), alert('Zapisano!');
      };
              
    <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"
    />
    

    【讨论】:

      【解决方案2】:

      您要么需要编写检查 null 的代码,从而向打字稿证明赋值是安全的:

      if (emailRef.current) {
        emailRef.current.value = '';
      }
      

      或者如果你知道它不可能为空,你可以使用非空断言。请注意,如果您这样做,typescript 将不会检查您的工作,因此如果您在它实际上可以为 null 时使用它,您将收到运行时错误。

      emailRef.current!.value = '';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 2019-11-10
        • 2022-01-08
        • 2021-12-01
        • 1970-01-01
        • 2019-11-16
        相关资源
        最近更新 更多