반응형
https://velog.io/@hygge31/forwardRef
forwardRef()
부모 컴포넌트에서 생성한 ref를 자식 컴포넌트로 전달해주는 역할.리액트가 제공하는 기본 컴포넌트인 <input>은 ref 속성에 값을 설정할 수 있지만,사용자 컴포넌트의 경우 ref 속성을 forwardRef 함
velog.io
forwardRef란?
부모 컴포넌트에서 생성한 ref를 자식 컴포넌트로 전달해주는 역할.
리액트가 제공하는 기본 컴포넌트인 <input>은 ref 속성에 값을 설정할 수 있지만,
사용자 컴포넌트의 경우 ref 속성을 forwardRef 함수로 전달해야함.
function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): 사용자_지정_반환_타입;
T: ref 대상 컴포넌트 (Ex. input 타입은 <HTMLInputElement>)
P: InputProps
export type reactInputProps = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>;
export type InputProps = reactInputProps & {};
input 사용자 컴포넌트에서 forwardRef 사용
import type { FC, DetailedHTMLProps, InputHTMLAttributes } from 'react'
import { forwardRef } from 'react'
export type reactInputProps = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
export type InputProps = reactInputProps & {}
export const Input = forwardRef<HTMLInputElement, InputProps>((props, ref) => {
const { className: _className, ...inputProps } = props
const className = ['input', _className].join(' ')
return <input ref={ref} {...inputProps} className={className} />
})
반응형
'React.js' 카테고리의 다른 글
[React] state prev 는 무엇인가? (0) | 2025.02.25 |
---|---|
[React.js + TypeScript] react-dnd 안쓰고 드래그앤 드랍 구현하기 (1) | 2025.02.02 |
[React] MutableRefObject와 LegacyRef (1) | 2025.01.21 |
[React.19] 메모이제이션이 필요 없는 리액트 컴파일러 (0) | 2024.10.18 |
React.memo, useMemo, useCallback 역할 및 차이점 (0) | 2024.10.02 |