【问题标题】:Ref object is possibly undefined TypeScript ReactRef 对象可能是未定义的 TypeScript React
【发布时间】:2020-05-11 02:17:40
【问题描述】:

我有一个组件,它使用钩子将输入值设置为组件状态。当输入值的长度超过 0 个字符时,我想添加一个类,但是我遇到了 TypeScript 说我的 ref 可能未定义的问题。

即使我检查 ref 是否存在于包装代码以添加类的条件中,我也无法摆脱这个错误。我不确定这个问题的解决方案。

错误: Object is possibly 'undefined' inputValue.current.classList.add(inputHasContentClassName);

import React, { useState, useEffect, useRef } from 'react';

const Component: React.FC = () => {
  const [inputValue, setInputValue] = useState('');
  const myRef = useRef();

  useEffect(() => {
    const inputHasContentClassName = 'input--has-value';

    if (inputValue.length > 0 && inputValue) {
      inputValue.current.classList.add(inputHasContentClassName);
    } else {
      inputValue.current.classList.remove(inputHasContentClassName);
    }
  }, [inputValue]);

  function handleInputChange(e: React.FormEvent<HTMLInputElement>) {
    setInputValue(e.currentTarget.value);
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    console.log('Submit form');
  }

  return (
    <>
      <section>
        <form onSubmit={handleSubmit}>
          <div>
            <input
              ref={myRef}
              onChange={handleInputChange}
              type="number"
            />
            <label>Input Label</label>
          </div>
          <button
            type="submit"
            disabled={inputValue.length === 0}
          >
            Submit
          </button>
        </form>
      </section>
    </>
  );
};

export default Component;

【问题讨论】:

  • 只添加一个 if like , if (myRef !== null) 然后做休息动作

标签: reactjs typescript


【解决方案1】:

useRef() 返回一个具有current 属性的对象,其中包含您真正关心的对象。在第一次渲染完成之前,current 属性将为空。这意味着该 ref 的类型是:

{ current: WhateverTypeYouCareAbout | null }

这意味着您必须将null 作为current 属性的可能值来处理。但是ref对象本身会一直存在,只是它的current属性可能是null。

我只需将您的 ref 的 current 值存储在一个变量中,测试它的存在,然后使用它。

  useEffect(() => {
    const inputHasContentClassName = 'input--has-value';
    const inputElement = inputValue.current;        

    if (inputElement && inputElement.value.length > 0) {
      inputElement.classList.add(inputHasContentClassName);
    } else {
      inputElement.classList.remove(inputHasContentClassName);
    }
  }, [inputValue]);

您还可以通过执行以下操作告诉 TypeScript 编译器您的 ref 的类型(在本例中为 HTMLInputElement):

const myRef = useRef<HTMLInputElement>();

【讨论】:

  • 这解决了最初的错误,但即使我检查 inputElement,我也会得到类型“never”上的“classList”不存在:inputElement &amp;&amp; inputElement.classList.add('classname')
  • 设法用const inputElement = (myRef.current as unknown) as HTMLInputElement; 解决了这个问题,但这感觉就像一个黑客。
  • 试试useRef&lt;HTMLInputElement&gt;();
  • @AlexWayne - 谢谢 :-) useRef&lt;HTMLInputElement&gt;();
  • 不要使用 ref 作为钩子依赖。这是不可靠的,因为改变 ref 不会触发重新渲染:stackoverflow.com/questions/60476155/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 2020-08-11
  • 2021-12-29
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多