interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
<P = {}>
props: PropsWithChildren
context
useContext
에서 사용하던 그 context!useContext
, Context.Consumer
를 통해 context의 값을 읽어올 수 있다.propTypes, contextTypes
defaultProps
displayName
type FC<P = {}> = FunctionComponent<P>;
<P>
와 동일한 역할을 수행한다./**
* @deprecated as of recent React versions, function components can no
* longer be considered 'stateless'. Please use `FunctionComponent` instead.
*/
type StatelessComponent<P = {}> = FunctionComponent<P>;
/**
* @deprecated - Equivalent with `React.FunctionComponent`.
*/
interface VoidFunctionComponent<P = {}> {
(props: P, context?: any): ReactElement<any, any> | null;
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
/**
* @deprecated - Equivalent with `React.FC`.
*/
type VFC<P = {}> = VoidFunctionComponent<P>;
@types/react
패키지를 통한 React 타이핑을 지원한다.<FC>
generic을 활용해 함수형 컴포넌트 타이핑이 가능하다.import { FC } from "react";
type UserProps = {
name: string;
cart: string[];
};
const UserBox: FC<UserProps> = ({ name, cart }) => {
return (
<div>
<div>name: {name}</div>
<div>cart: {cart.length}</div>
</div>
);
};
// 1. 익명 함수를 변수에 할당하여 타이핑하기
const UserBox: FC<UserProps> = function ({ name, cart }) {
return ( ... );
};
// 2. 화살표 함수 사용하기
const UserBox = FC<UserProps> = ({name, cart}) => {
return (...) ;
}
function UserBox({name, cart} : UserProps) {
return (...)
}
type UserGeneric<T> = {
name: string;
cart: T;
};
const UserBoxWithGeneric: <T>(props: UserGeneric<T>) => {};
위처럼 generic을 사용하는 컴포넌트를 React.FC에서는 어떻게 작성할 수 있을까?
🤗 없다!
사실 엄청 간단한 이유인데,
const UserBoxWithGenericAndFC: React.FC</*...*/> = <T,>(
props: UserGeneric<T>
) => {};
위처럼 generic 문법을 사용한 React.FC 컴포넌트를 만들 경우, 컴포넌트에 generic 값을 전달할 수 있는 방법이 따로 없기 때문이다.
React 18 버전으로 업데이트 되기 전, React.FC는 type이 ReactNode
인 children을 암시적으로 가졌다.
원래 TS의 의도대로라면, React.FC를 사용하지 않은 아래의 방법처럼 children을 다루고 있지 않은 컴포넌트에 children을 넘겨줄 경우 에러로 처리해야 했다.
function UserBox2({ name }: { name: string; cart: number }) {
return (
<h1>
{name}: {cart}
</h1>
);
}
const App = () => (
<>
<UserBox2 name="Stefan">
<span>{"I can set this element but it doesn't do anything"}</span>
</UserBox2>
</>
);
const UserBox: FC<UserProps> = ({ name, cart }) => {
return (
<h1>
{name}: {cart}
</h1>
);
};
const App = () => (
<>
<UserBox name="Stefan">
<span>{"I can set this element but it doesn't do anything"}</span>
</UserBox>
</>
);
🤖 이러한 이유로, CRA에서는 React.FC를 사용하지 않기로 결정했다.
type Props = {
children: React.ReactNode;
};
const CodeSnippet: React.FC<Props> = ({ children }) => <div>{children}</div>;