본문 바로가기
React

forwardRef

by kicksky 2021. 11. 22.

react에는 두 종류의 ref가 있다; ref 객체, ref 콜백.

  • 전자는 useRef로 만들어지며 current 프로퍼티를 갖는 객체; RefObject. T는 current에 할당되는 값의 타입이다.
  • 후자의 경우, 엘리먼트에 함수를 넘겨주면 인스턴스가 생성되거나 사라질 때 해당 함수가 콜백된다; (instance: T) => void

둘 모두를 가리키는 건 Ref. ref를 prop으로 넘겨 받기만 한다면 그 컴포넌트는 Ref로 충분. 이 때 ref는 객체일 수도, 함수일 수도 있다.
그러나 해당 Ref를 컴포넌트 내에서 ref Object로 활용하려면 타입의 범위를 RefObject로 좁혀야 한다. 

 

하나 더, 범위를 제한하지 않으면서 ref를 활용하고 싶다면

interface ExampleProps {
  buttonRef: Ref<HTMLButtonElement>
}

const Example: FC<ExampleProps> = ({ buttonRef }) => {
  const myRef = useRef<HTMLButtonElement>(null);
  useEffect(() => {
    console.log(myRef.current);
  });
  return (
    <div>
      <button ref={(element) => {
        (myRef as MutableRefObject<HTMLButtonElement>).current = element;
        if (typeof buttonRef === 'function') {
          buttonRef(element);
        } else {
          buttonRef.current = element;
        }
      }}>Hello</button>
    <div>
  )
}

as MutableRefObject에 해당하는 type assertion이 필요한 이유는 myRef가 immutable하기 때문이다. (MutableRefObject가 아니라 RefObject)

이 때, .current는 read-only이다. 일반적으로 .current는 런타임에서 변하지 않고 react가 이를 대신 한다.

 

stackoverflow #1
stackoverflow #2

'React' 카테고리의 다른 글

Lazy-loading  (0) 2021.05.08
Kakao Map API에서 마우스 이벤트 핸들링  (0) 2021.04.07
Rendered more hooks than during the previous render  (0) 2021.03.28
Brad Westfall, React: "mount" vs "render"  (0) 2021.02.13

댓글