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;
'공부기록 > Typescript' 카테고리의 다른 글
# 65 Context Api 타입지정 (0) | 2023.11.16 |
---|---|
# 58 Form 래퍼 컴포넌트 타입지정 (0) | 2023.11.15 |
# 54 polymorphic component 만들기 : Container (0) | 2023.11.15 |
# 50 타입의 다양한 활용 유니언 타입, ComponentPropsWithoutRef, Button컴포넌트 (0) | 2023.11.15 |
useState / Formevent /setState / useRef 타입지정 (0) | 2023.11.15 |