1) HTMLAtrributes의 파생타입을 제네릭으로 받아서 해당 타입을 반환
태그 속성들의 타입들을 가져올수있음
import {InputHTMLAttributes, DetailedHTMLProps} from "react";
type Props = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
2) 원래의 input 속성이 아니지만, input 컴포넌트 만들때 필요한 값들이 있을경우
별도의 타입을 선언하고 Props 뒤에 & 연산자를 사용해서 붙여줌
(사용할땐 props로 접근하기 예: props.label)
type InputValue = { // 추가로 전달하고 싶은 속성들은 여기서
label: string
}
React.forwardRef<HTMLInputElement, Props & InputValue>((props, ref) => { // type들 사용 이유
그 중에서 ref도 input 컴포넌트에 전달되어야 함.
1) React.forwardRef를 사용해줘야 함.
함수형 컴포넌트에서는 기본적으로 ref를 자식 컴포넌트에게 props로 넘겨줄수 없다고 한다.
💡 그렇지만!!
React.forwardRef는 ref를 자식 컴포넌트에 전달할 수 있게 해주는 함수다.
2) type은 HTMLInputElement으로 지정해줘야 함
나는 enum을 만들고 사용했다면 tree-shaking될 필요가 없고 써도 되는거 아닐까라는 생각이 들었고,
line의 기술 블로그도 보고, 다른 의견의 블로그도 보았을때 enum을 마냥 지양하는게 답은 아니겠다 생각을 했다.
enum에서 에러가 났었음
에러내용 : 'QuestionList' cannot be used as a value because it was imported using 'import type'.ts(1361)
export {QuestionList}; // enum인 경우 그냥 export
export type {FormValue}; // enum을 제외한 나머지 타입들은 export type
import { QuestionList } from "../../types/join"; // enum인 경우 그냥 export
import type { FormValue } from "../../types/join"; // enum을 제외한 나머지 타입들은 export type
import React, {InputHTMLAttributes, DetailedHTMLProps} from "react";
type Props = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>; // 1번 해결점
const Input = React.forwardRef<HTMLInputElement, Props>((props, ref) => {// 2번 해결점
return <input ref={ref} {...props}/>;
});
export default Input;
react-hook-form + yup + forwardRef()를 이용한 input 컴포넌트 제작하기, 오류해결
React-Re-rendering-과-최적화
Carrot-market-정복-노트-6-React-Hook-Form
⭐️리액트에서 기본 컴포넌트를 만들때
⭐️자식-컴포넌트의-ref에-접근하는-법
⭐️'타입스크립트 enum 을 사용하지 않는 방법' 을 사용하지 않는게 좋은 이유