ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [ React ] "props" 는 무엇일까?
    TIL 2024. 1. 19. 22:07
    728x90

     

     

    Props란 ?

    props는 컴포넌트끼리의 정보교환 방식이다. props는 간단하게 말하면 부모 컴포넌트가 자식 컴포넌트에게 물려준 데이터이다. 다시 말해, 컴포넌트 간의 정보 교류 방법이다.

    1. props는 반드시 위에서 아래 방향으로 흐른다. [부모] --> [자식] 방향으로만 흐른다 ( 단방향 ).
    2. props는 반드시 읽기 전용으로 취급하며, 변경하지 않는다.

     

     

    출처: https://bosctechlabs.com/react-state-vs-props-introduction-differences/

     

     

    아직 블로그에 state에 대해 작성하지는 않았지만

    상위 컴포넌트에서 하위 컴포넌트로 어떻게 props가 이루어지는지 이해하기 좋아서 이미지를 가져와봤다. 

     

    수업에서 배운 내용을 가져와 props에 대해 복습해보려한다.

     

    // src/App.js
    
    import React from "react";
    
    function App() {
      return <GrandFather />;
    }
    
    function GrandFather() {
      return <Mother />;
    }
    
    function Mother() {
    	const name = '홍부인';
      return <Child />;
    }
    
    function Child() {
      return <div>연결 성공</div>;
    }
    
    
    export default App;

     

    위의 코드는 <GrandFather />를 리턴하는데

     return <GrandFather />; 부터 아래를 향해 순서대로 자식요소를 타고 가면 

    결국 <GrandFather />은 function Child ( ) 에서 <div>연결 성공<div> 을 화면에 나타낸다.

     

    그런데 Mother 컴포넌트에 있는 mother의 이름 '흥부인'은 어떻게해야 Child 컴포넌트에서 Mother의 이름을 알 수 있을까?

     

    // src/App.js
    
    import React from "react";
    
    function App() {
      return <GrandFather />;
    }
    
    function GrandFather() {
      return <Mother />;
    }
    
    function Mother() {
    	const name = '홍부인';
      return <Child motherName={name} />; // 💡"props로 name을 전달했다."
    }
    
    function Child() {
      return <div>연결 성공</div>;
    }
    
    
    
    export default App;

     

    만약 Mother 컴포넌트가 가지고 있는 정보(값)을 Child에게 주고 싶을 때는

    motherName 이라는 이름으로 name 값을 Child 컴포넌트에게 전달해준다.

    이 과정을 "Props 로 정보를 전달했다" 라고 표현한다.

     

     

    그럼 Mother 컴포넌트가 전달한 motherNameChild가 어떻게 받을 수 있을까?

    function Child(props){
    	console.log(props) // 이게 바로 props다.
    	return <div>연결 성공</div>
    }

     

    이렇게 Child 컴포넌트에 props를 통해 받을 수 있다.

    props 란 결국 부모 컴포넌트가 자식에게 넘겨준 데이터들의 묶음이라고 볼 수 있다.

    우리는 이제 props 를 통해 부모 컴포넌트로부터 자식 컴포넌트에게 데이터를 넘겨줬다.

     

    이제 어떻게 Mother 컴포넌트에게 받은 motherName을 렌더링 할까?

     

    import React from "react";
    
    // div안에서 { } 를 쓰고 props.motherName을 넣어보세요.
    function Child(props) {
      return <div>{props.motherName}</div>;
    }
    
    function Mother() {
      const name = "홍부인";
      return <Child motherName={name} />;
    }
    
    function GrandFather() {
      return <Mother />;
    }
    
    function App() {
      return <GrandFather />;
    }
    
    export default App;

     

    propsobject literal 형태이기 때문에 { props.motherName } 로 꺼내서 사용할 수 있다.

    object literalkeymotherName 인 이유는 우리가 Child로 보내줄 때 

    motherName = { name } 으로 보내주었기 때문이다. 

     

    💡 추가적인 정보들


    - JSX에서는 { } 중괄호를 사용하면 자바스크립트 코드를 사용할 수 있다.
    - 자식 컴포넌트에서 부모 컴포넌트로 props 를 전달할 수 없다. 오직 부모 --> 자식으로만 !
    728x90
Designed by Tistory.