본문 바로가기
JavaScript/React

[React] #2.1 Reusable Components with JSX + Props (#코딩공부)

by 함께 공부해요 2020. 5. 19.

https://youtu.be/POP_pXZwvDg


<복습>

https://wook-2124.tistory.com/127

 

[React] #2.0 Creating your first React Component (#코딩공부)

https://youtu.be/9OGzwWVImU0 <복습> https://wook-2124.tistory.com/126 [React] #1.2 How does React work (#코딩공부) https://youtu.be/9yITc-uEjwI <복습> https://wook-2124.tistory.com/125 [React] #1.1..

wook-2124.tistory.com

 

<준비물>

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com


1. props(property, 소유품)

Potato.js에 적었던 function Potato component를 index.js에서 rendering(표현)하고 있는 App.js에 몰아서 작성했다.

 

결국 index.js가 rendering(표현)되고 있는 것은 App() component이기 때문에 <h1> 다음에 <Potato />가 rendering(표현)된다.

 

Potato component를 Food component로 바꾸고, fav라는 예약어 'props'(property 소유물)로 kimchi라는 value(값)을 줬다.

 

function Food component에 원하는 만큼 props(fav, isHot, kindsOf)를 추가할 수 있고, React는 Food component의 모든 props(fav, isHot, kindsOf)를 Food component의 parameter(매개변수)로 넣은 뒤 argument(인자)로 사용한다.

 

function Food(props)의 실행으로 console.log로 나온 Object는 Food component의 argument(인자)로써 function App()에 적힌 children Food로부터 parent Food로 전달된 모든 props(fav, isHot, kindsOf)이다.


2. props 응용하기

children Food의 props에서 fav만 가져오려면 props.fav를 적어주면 되고, 그럼 props.fav의 value인 kimchi가 출력된다. props의 value는 function Food component의 parameter(매개변수)인 props의 argument(인자)라고 생각하면 된다.

 

props.fav = { fav } 이다. 쉽게 설명하면 props.fav로 치는 것은 번거로우니 component의 { }(props)안에서 fav자체를 가져온 것이다.

 

<h3>문구에 {fav}를 써서 keyword argument화했다. {fav}는 Food component props(fav)의 value인 kimchi를 argument(인자)로써 호출한다.


3. JSX+props의 힘으로 재사용하기

JSX는 단지 HTML+JavaScript이다. 때문에 component는 대문자(Food, App, Potato)로 시작해야하고, 그 뒤에 fav처럼 props를 정해서 그에 해당하는 value를 argument(인자)로써 parent component로 보낼 수 있다.

 

결국 children component의 props는 fav든 like든 isHot이든, 짓는 이름과 상관없이 parent component에 넣는 정보이다. props의 value(kimchi, ramen, apple, pizza)는 parent function Food component의 parameter(매개변수)인 props의 argument(인자) 역할을 하게된다.

댓글