Ref 对象可能是未定义的 TypeScript React

Ant*_*ish 12 typescript reactjs

我有一个组件,它使用钩子将输入值设置为组件状态。当输入值的长度超过 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;
Run Code Online (Sandbox Code Playgroud)

Ale*_*yne 18

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

{ current: WhateverTypeYouCareAbout | null }
Run Code Online (Sandbox Code Playgroud)

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

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

  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]);
Run Code Online (Sandbox Code Playgroud)

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

const myRef = useRef<HTMLInputElement>();
Run Code Online (Sandbox Code Playgroud)

  • 尝试 `useRef&lt;HTMLInputElement&gt;();` (23认同)
  • @AlexWayne - 谢谢你:-) ```useRef&lt;HTMLInputElement&gt;(); ```` (3认同)