HTML 요소에 전달할 수 있는 참조를 살펴봅시다.
대부분의 HTML 요소는 ref를 허용하며, 이는 지금까지 useRef
를 통해 살펴본 것과 같은 형태입니다.
이 예제에서 div
를 마우스로 가리키면 JSX.IntrinsicElements.div
라는 것을 알 수 있습니다.
export const nullAsRef = (
<div
ref={{
current: null,
}}
></div>
);
ref
를 CMD + Click
하면 타입 정의로 이동하여 ref
가 LegacyRef
이거나 undefined
인 것을 보여줍니다.
interface ClassAttributes<T> extends Attributes {
ref?: LegacyRef<T> | undefined;
}
이 참조에 여러 가지 다른 것을 전달할 수 있습니다. current
가 null
로 설정된 객체나 HTML 요소일 수 있습니다.
하지만 임의의 문자열이나 undefined
로 설정할 수는 없습니다.
export const undefinedAsRef = (
<div
ref={{
// Type 'undefined' is not assignable to
// type 'HTMLDivElement | null'.
current: undefined,
}}
></div>
);
React는 연결된 엘리먼트가 unmounted될 때 참조를 null
로 설정하기 때문에 undefined
참조를 전달할 수 없습니다.
div
에 참조를 전달하면 React가 해당 참조를 관리하고 div가 unmount 될 때 null
로 설정합니다.
문자열을 참조로 전달할 수 있는 레거시 React API가 지원됩니다.
export const stringAsRef = <div ref={"legacyRef"}></div>;
stringAsRef
를 CMD + Click
하면 string
또는 Ref<T>
가 될 수 있는 LegacyRef로 입력된 것을 볼 수 있습니다.
type React.LegacyRef<T> = string | Ref<T>