- 리액트에서 HTML 태그의 속성 타입을 활용하는 대표적인 2가지 방법은
DetailedHTMLProps
와ComponentWithoutRef
타입을 활용하는 것이다.
DetailedHTMLProps
DetailedHTMLProps
타입을 활용하면 쉽게 HTML 태그 속성과 호환되는 타입을 선언할 수 있다.ButtonProps
의onClick
타입은 실제 HTML button 태그의 onClick 이벤트 핸들러 타입과 동일하다.
type NativeButtonProps = React.DetailedHTMLProps< React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement >; interface ButtonProps { onClick?: NativeButtonProps['onClick']; };
ComponentPropsWithoutRef
CircleButtonProps
의onClick
타입은 실제 HTML button 태그의 onClick 이벤트 핸들러 타입과 동일하다.
type NativeButtonType = React.ComponentPropsWithoutRef<'button'>; interface CircleButtonProps { onClick?: NativeButtonType['onClick']; }
- 리액트 18버전 기준 함수형 컴포넌트에
ref
를 전달하기 위해서는forwardRef
를 사용해야 한다. 이런 경우ComponentWithoutRef
를 사용하여 props와 ref를 분리할 수 있다. (리액트 19버전부터는 바로 전달할 수 있다.) React.ComponentPropsWithoutRef<'button'>
로 작성하면 button 태그에 대한 HTML 속성을 모두 포함하지만, ref 속성은 제외된다.
type NativeButtonType = React.ComponentPropsWithoutRef<'button'>; const Button = forwardRef<HTMLButtonElement, NativeButtonType>((props, ref) => { return ( <button ref={ref} {...props}> 버튼 </button> ); }); const ButtonWrap = (props: NativeButtonType) => { const buttonRef = useRef(null); return ( <div> <Button ref={buttonRef} {...props} /> </div> ); };
'TypeScript' 카테고리의 다른 글
[TS] 리액트 이벤트, 제네릭 컴포넌트, HTMLAttributes (0) | 2025.02.12 |
---|---|
[TS] Superstruct (0) | 2025.02.04 |
[TS] 컴파일러 구조 (0) | 2025.02.01 |
[TS] 런타임과 컴파일 (0) | 2025.01.31 |
[TS] Record 원시 타입 키 개선 (1) | 2025.01.30 |