Function Component
타입의 줄임말이다.
interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
type FC<P = {}> = FunctionComponent<P>;
PropsWithChildren<P>
를 사용하여 children props를 포함한다.defaultProps
, propTypes
, displayName
의 prop로 포함defaultProps
, propTypes
, displayName
등의 정적 속성을 쉽게 사용 가능하다.children
이 항상 포함된다.React.FC
를 사용할 경우 props
에 자동으로 children
이 옵셔널로 들어가있다.
→ 단점인 이유는 children
의 명확하지 않은 타입 지정이기 때문이다.
→ 모든 컴포넌트를 React.FC
로 선언했을 때 children
이 필요하지 않은 컴포넌트에도 명시를 해놓지 않았기 때문에 children
을 사용할 수 있는 문제가 발생한다.
현재 만들어둔 Chip 컴포넌트는 이렇게 구성되어 있다.
export const Chip: React.FC<ChipProps> = ({
className,
variant = 'default',
size = 'sm',
children,
...props
}) => {
const chipClass = cn(
chipStyles.base,
chipStyles.variant[variant],
chipStyles.size[size],
className,
);
return (
<button className={chipClass} {...props}>
<div className="size-18 rounded-6 border border-slate-200 bg-white">
{variant === 'active' && <FaCheck className="size-16 text-blue-600" />}
</div>
{children}
</button>
);
};
이러한 방식으로 바꿔야 children
에 대한 명확한 타입 지정이 가능하다.
export const Chip = ({
className,
variant = 'default',
size = 'sm',
children,
...props
}: ChipProps) => {
const chipClass = cn(
chipStyles.base,
chipStyles.variant[variant],
chipStyles.size[size],
className,
);
return (
<button className={chipClass} {...props}>
<div className="size-18 rounded-6 border border-slate-200 bg-white">
{variant === 'active' && <FaCheck className="size-16 text-blue-600" />}
</div>
{children}
</button>
);
};
React.FC 정의
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts