12-3 props
( properties )
함수에 어떤 데이터를 전달 할 때 매개변수를 통해 전달하는 것 처럼, 리액트(/컴포넌트)에서도 비슷한 개념으로, 데이터를 전달할 때 Props를 사용해서 전달합니다. props = 매개변수
import React from 'react';
const MyWeather : React.FC = (props) => {
return (
<div>
오늘의 날씨는 {props.weather} 입니다.
</div>
)
}
export default MyWeather;
React.FC : FC(functional component)의 타입을 선언합니다.1️⃣
const MyWeather : React.FC = (props) => {
const MyWeather : React.FC<string> = (props) => {
처럼 단순히 string 라고 할 수도 있고
2️⃣
interface MyProps{
weather : string;
}
const MyWeather : React.FC<MyProps> = (props) => {
인터페이스를 사용하여 좀 더 명확하게 지정이 가능합니다.
<App.tsx>
function App() {
return (
<div>
<MyWeather weather ='value'></MyWeather>
</div>
)
}
-------------------------------
<MyWeather.tsx>
~
const MyWeather : React.FC<string> = (props) => {
return (
<div>
오늘의 날씨는 {props.weather} 입니다.
</div>
)
}
컴포넌트 재사용 가능컴포넌트의 태그 사이에 위치한 요소를 children 이라고 합니다.
해당 컴포넌트의 자식요소를 나타냅니다.
interface MyProps{
weather : string;
children : React.ReactNode; // React.ReactNode = 컴포넌트의 자식요소라는 의미
}
<MyWeather weather='맑음'>날씨</MyWeather>
//---------------------
~
{props.children} {props.weather} ===> 날씨 맑음
~
import React from 'react';
interface MyProps {
weather: string;
children: React.ReactNode;
}
const MyWeather: React.FC<MyProps> = ({ weather, children }) => {
//const {children, weather} = props;
return (
<div>
<p>{children}</p>
오늘의 날씨는 {weather}입니다.
</div>
);
};
export default MyWeather;