항상 발전하는 개발자 2023. 9. 20. 01:09
728x90

Props란?

  • properties를 줄인 표현으로 컴포넌트 속성을 설정할 때 사용하는 요소
  • props는 컴포넌트끼리 값을 전달하는 수단
  • 상위 컴포넌트에서 하위 컴포넌트로 전달(단방향 데이터 흐름)
  • 공식 문서에 따르면 props를 아래와 같이 요약한다.
- To pass props, add them to the JSX, just like you would with HTML attributes.
- To read props, use the 'function Avatar({ person, size })' destructuring syntax.
- You can specify a default value like 'size = 100', which is used for missing and 'undefined' props.
- You can forward all props with '<Avatar { . . . props} />' JSX spread syntax, but don't overuse it!
- Nested JSX like '<Card><Avatar /></Card>' will appear as 'Card' component's 'children' prop.
- Props are read-only snapshots in time: every render receives a new version of props.
- You can't change props. When you need interactivity, you'll need to set state.
https://react.dev/learn/passing-props-to-a-component
 

Passing Props to a Component – React

The library for web and native user interfaces

react.dev


함수형 컴포넌트 props

  • 부모 컴포넌트에서 전달한 props는 함수형 컴포넌트에서 함수의 파라미터로 전달받으며, JSX 내부에서 { } 기호로 감싸서 사용한다. 

  • 자식 컴포넌트 코드
    • 원래는 props를 쓰지만 { } 을 통해 구조분해 할당 가능
    • ttitle, author, price, type props 받음 
    • function FunctionPropsComponent(props)인 경우
      • {props.title} , {props.author}, {props.price}, {props.type} 
    • function FunctionPropsComponent({title, author, price, type})인 경우
      • {title}, {author}, {price}, {type} 
  • defaultProps
    • 부모 컴포넌트에서 props가 전달되지 않았을 때 기본값으로 보여줄 props를 설정하는 것
  • propTypes
    • 컴포넌트의 필수 props를 지정하거나 props의 타입을 지정할 때 사용
    • JavaScript의 "유연한 특성"을 해결하기 위해 권장되는 기능
    • 정해진 타입이 아닌 다른 타입으로 정보가 전달될 시, 제대로 동작은 하지만 console에 오류가 나온다.
import PropTypes from "prop-types";

function FunctionPropsComponent(props) {
  const { title, author, price, type } = props;
  const style = {
    textAlign: "-webkit-center",
  };
  const divStyle = {
    backgroundColor: "#ffffc2",
    textAlign: "center",
    width: "550px",
  };
  const imgStyle = {
    height: "200px",
  };
  const textStyle = {
    textAlign: "initial",
    marginLeft: "90px",
  };
  return (
    <div style={style}>
      <div style={divStyle}>
        <h2>이번주 베스트셀러</h2>
        <img src="img/book.jpg" alt="book" style={imgStyle}></img>
        <h2>{title}</h2>
        <div style={textStyle}>
          <h4>저자: {author}</h4>
          <h4>판매가: {price}</h4>
          <h4>구분: {type}</h4>
        </div>
      </div>
    </div>
  );
}


FunctionPropsComponent.defaultProps = {
title= "하하",
author="호호",
price="12,000",
type="소설",
}


FunctionPropsComponent.propTypes = {
  title: PropTypes.string,
  author: PropTypes.string,
  price: PropTypes.number,
  type: PropTypes.string,
};

export default FunctionPropsComponent;

  • 부모 컴포넌트 코드
    • ttitle, author, price, type props 전달
import FunctionPropsComponent from "./FunctionPropsComponent";
function App(){
	return(
   	<>
      <FunctionPropsComponent
        title="나의 하루는 4시 40분에 시작된다."
        author="김유진"
        price="13,500원"
        type="자기계발서"
      ></FunctionPropsComponent>
    </>
    );
}

export default App;

클래스형 컴포넌트 props

  • 함수형 컴포넌트 props와 동일하게 사용하지만 불러오는 코드만 살짝 다르다. 
  • {this.props.name}으로 props앞에 this를 붙여야 한다.

  • 자식 컴포넌트 코드
    • 구조분해 할당도 가능
    • {this.props.food}
import { Component } from "react";

import PropTypes from "prop-types";

class ClassPropsComponent extends Component {
  render() {
    const { food } = this.props;
    const style = {
      color: "red",
    };

    return (
      <h2>
        저는 <span style={style}>{food}</span>를 좋아합니다.
      </h2>
    );
  }
}

ClassPropsComponent.defaultProps = {
  food: "바나나",
};

ClassPropsComponent.propTypes = {
  food: PropTypes.string,
};
export default ClassPropsComponent;

※ props.children

  • 부모 컴포넌트에서 자식 컴포넌트를 호출할 때 태그 사이에 작성한 문자열
  • 자식 컴포넌트
    • {props.children} 사용

  • 부모 컴포넌트

728x90