정의
클래스형 컴포넌트(예전)
함수형 컴포넌트(현재)
children
PropsWithChildren
import React, { PropsWithChildren } from "react";
interface CardProps {
title: string;
}
const Card: React.FC<PropsWithChildren<CardProps>> = ({ title, children }) => {
return (
<div style={{ border: "5px solid #ccc", padding: "10px", margin: "10px" }}>
<h2>{title}</h2>
<div>{children}</div>
</div>
);
};
function App() {
return (
<div>
<Card title="1.카드">
<p>카드 입니다</p>
</Card>
</div>
);
}
export default App;
import React, { PropsWithChildren } from "react";
// Container 컴포넌트 정의
interface ContainerProps {
backgroundColor: string;
}
const Container: React.FC<PropsWithChildren<ContainerProps>> = ({
backgroundColor,
children,
}) => {
return (
<div style={{ backgroundColor, padding: "20px", margin: "10px" }}>
{children}
</div>
);
};
// 사용 예시
function App() {
return (
<div>
<Container backgroundColor="lightblue">
<p>이것은 첫 번째 컨테이너입니다.</p>
</Container>
<Container backgroundColor="lightgreen">
<p>이것은 두 번째 컨테이너입니다.</p>
</Container>
</div>
);
}
export default App;
ReactNode
React.FunctionComponent
children 사용 시 주의할 점
Prop-types
import React from 'react';
import PropTypes from 'prop-types';
const MyComponent = ({ title, age }) => {
return (
<div>
<h1>{title}</h1>
{age && <p>Age: {age}</p>}
</div>
);
};
// PropTypes 정의
MyComponent.propTypes = {
title: PropTypes.string.isRequired, // title은 필수 prop
age: PropTypes.number, // age는 선택적 prop
};
export default MyComponent;
변수 / 함수