Ref 전달

TERABYTE·2021년 10월 6일
0

ref를 props로 내려줄 수 없음
꼼수로 innerProps로 만들어서 내릴 수 있으나 정석은 아님

부모의 Ref를 자식에게 넘겨주기 위해서는 forwardRef를 사용해야한다

interface Props {
  placeholder?: string
  name?: string
  type?: "text" | "number" | "password" | "email"
  value?: string
  disabled?: boolean
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
  ref?: React.RefObject<HTMLInputElement>
}

export function Input({
  placeholder,
  name,
  type,
  value,
  disabled,
  onChange,
  ref,
}: Props) {
  
  const InputRef = forwardRef<HTMLInputElement, Props>((props, ref) => {
    return <input className={style.input} ref={ref} {...props} />
  })

  InputRef.displayName = "InputRef"

  return (
    <InputRef
      type={type ? type : "text"}
      name={name}
      placeholder={placeholder}
      value={value}
      disabled={disabled}
      onChange={onChange}
      ref={ref}
    />
  )
}

Ref를 사용하면 컴포넌트의 종속성이 생길 수 밖에 없다.
유지보수를 할 나를 위해 남발하지 않도록 조심하자

profile
애기개발자😎

0개의 댓글