본문 바로가기

공부기록/Typescript

#57 forwardRef의 타입지정

forwardRef의 타입지정

 


ComponentPropsWithRef로 변경

 

type InputProps = {
  label: string;
  id: string;
} & ComponentPropsWithRef<"input">;

 

 

 

에러 forwardRef 활용하라는 의미 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

해결방법 : 

 

리액트 함수 forwardRef 로 감싸고 ref를 매개변수로 받기 

 

 

 

type InputProps = {
  label: string;
  id: string;
} & ComponentPropsWithRef<"input">;

const Input = forwardRef(({ label, id, ...props }: InputProps, ref) => {
  return (
    <p>
      <label htmlFor={id}>{label}</label>
      <input id={id} type="text" {...props} ref={ref} />
    </p>
  );
});

export default Input;

 

 

 

에러 : forwardRef는 unknown value를 참조하고 있음


 

 

 

 

 

해당 ref객체에서 어떤 값이 최종적으로 수신될 것인지를 알 수 없어서 나오는 에러 

추가 type정보를 제공해야 함 

 

 

지금은 값 type이며 ref에 저장될 것.

 

 

다음 에러가 발생 

 


 

 

forwardRef는 두가지 제네릭 타입을 받음

 

두번째는 InputProps.

 

 

 

import { forwardRef, type ComponentPropsWithRef } from "react";

// type InputProps = {
//   label: string;
//   id: string;
// } & ComponentPropsWithoutRef<"input">;

type InputProps = {
  label: string;
  id: string;
} & ComponentPropsWithRef<"input">;

const Input = forwardRef<HTMLInputElement, InputProps>(
  ({ label, id, ...props }: InputProps, ref) => {
    return (
      <p>
        <label htmlFor={id}>{label}</label>
        <input id={id} type="text" {...props} ref={ref} />
      </p>
    );
  }
);

export default Input;