12-3 props

airbus·2025년 4월 10일

프로그래머스

목록 보기
53/93

12-3 props

props


( properties )

함수에 어떤 데이터를 전달 할 때 매개변수를 통해 전달하는 것 처럼, 리액트(/컴포넌트)에서도 비슷한 개념으로, 데이터를 전달할 때 Props를 사용해서 전달합니다. props = 매개변수

import React from 'react';

const MyWeather : React.FC = (props) => {
    return (
        <div>
            오늘의 날씨는 {props.weather} 입니다.
        </div>
    )
}

export default MyWeather;
  • 리액트, 자바스크립트와 달리 타입스크립트에서는 전달받는 props는 타입도 명확히 설정해야합니다.
    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>
    )
}
  • App.tsx에서 value의 값은 MyWeather.tsx의 props에 전달이 되고, 전달받은 props는 props.weather에서 출력합니다.
    => 오늘의 날씨는 vlaue 입니다. // 날씨(데이터)가 고정되어있는게 아니라, 동적으로 변합니다. = 컴포넌트 재사용 가능

props > children

컴포넌트의 태그 사이에 위치한 요소를 children 이라고 합니다.
해당 컴포넌트의 자식요소를 나타냅니다.

  • children 요소를 사용하기 위해서는 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;

0개의 댓글