programing

Ref 개체가 정의되지 않은 TypeScriptReact일 수 있습니다.

mailnote 2023. 7. 15. 10:26
반응형

Ref 개체가 정의되지 않은 TypeScriptReact일 수 있습니다.

후크를 사용하여 입력값을 구성요소 상태로 설정하는 구성요소가 있습니다.입력 값이 0자 이상일 때 클래스를 추가하고 싶은데 TypeScript에서 내 참조가 정의되지 않았을 수 있다고 하는 문제가 발생했습니다.

클래스를 추가하기 위해 코드를 랩하는 조건부에 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;

useRef()객체를 반환합니다.current속성, 실제로 중요한 개체를 포함합니다.그리고 첫 번째 렌더링이 완료되기 전에,current속성이 null이 됩니다.즉, 기준의 유형은 다음과 같습니다.

{ current: WhateverTypeYouCareAbout | null }

그리고 그 말은 당신이 처리해야 한다는 것을 의미합니다.null의 가능한 가치로서.current소유물.하지만 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]);

또한 TypeScript 컴파일러에게 ref의 유형을 알려줄 수 있습니다(이 경우).HTMLInputElement) 다음을 수행합니다.

const myRef = useRef<HTMLInputElement>();

언급URL : https://stackoverflow.com/questions/59901775/ref-object-is-possibly-undefined-typescript-react

반응형