React의 props.children
패턴을 사용하면 부모 컴포넌트에 자식 컴포넌트를 전달한 다음 트리에서 부모 컴포넌트 아래에 자식 컴포넌트가 표시되도록 할 수 있습니다.
export const Button = (props: {}) => {
return <button>{props.children}</button>;
};
const Parent = () => {
return (
<>
{/* @ts-expect-error */}
<Button></Button>
<Button>Hello world!</Button>
</>
);
};
많은 팀이 children
을 any 타입으로 합니다.
export const Button = (props: {
children: any;
}) => {
...
이는 어느 정도 허용되지만, 실제로는 타입스크립트에서 이를 정의하는 더 적절한 방법이 있습니다.
props.children
에 대한 적절한 타입 정의를 찾는 것이 과제입니다.
이를 처리하는 올바른 방법은 프로퍼티에 자식을 추가하고 이를 React.ReactNode
로 입력하는 것입니다.
export const Button = (props: { children: React.ReactNode }) => {
return <button>{props.children}</button>;
};
React.ReactNode
는 자식을 전달할 수 있는 다양한 경우를 모두 다룹니다.
React.ReactChild
를 사용하고 싶으셨을 수도 있지만, 이 기능은 더 이상 사용되지 않습니다.
React.ReactNode
's Type DefinitionsCMD + Click
을 사용하여 React.ReactNode
의 타입 정의를 탐색하면 잠재적으로 들어 갈 수 있는 다양한 것들을 볼 수 있습니다. React.ReactElement
, string
, number
, React.ReactFragment
, React.ReactPortal
, boolean
, null
, or undefined
등이 있습니다.
일종의 도우미 역할을 하는 셈입니다.