react-js로 웹 서비스 만들기 2

·2020년 5월 19일
0

좌충우돌

목록 보기
3/26

2. jsx & props

(1) component

// src/index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
// App.js의 컨테이너가 public/index.html의 root id 아래에 들어가게 되는 원리

ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById("root")
);
// src/App.js
import React from "react";
import Potato from "./Potato";

function App() {
    return (
        <div>
            hello
      	{/* Potato.js의 내용이 컨테이너로 App에 들어가게 됨 */}
            <Potato></Potato>
        </div>
    );
}

export default App;
// src/Potato.js
import React from 'react'

function Potato(){
    return (
        <h1>hello potato</h1>
    );
}

export default Potato;

그래서 container안에 container 넣고, 또 그 container에 container 넣고 등등을 할 수 있음.
그런데 굳이굳이 이렇게 파일을 분리할 필요는 없고, App.js에 모든 Potato를 function으로 집어넣어서 하나로 퉁 칠 수도 있다.

// src/App.js
import React from "react";

function Potato({ fav, image, rating }) {
    return (
        <h4>
            I am talking Potato...
            <br></br>
            with {fav}
            <br></br>
            score: {rating}
            <br></br>
            which looks like this
            <br></br>
            <img src={image} width="200" height="100" alt={fav}></img>
        </h4>
    );
}

const kinds = [
    { id: 1, name: "cheese", image: "https://i.ytimg.com/vi/2WU59bSygeA/maxresdefault.jpg", rating: 4.3 },
    { id: 2, name: "kimchi", image: "https://recipe1.ezmember.co.kr/cache/recipe/2015/04/18/41ff68622521fa4abaed787c4c8eafb31.jpg", rating: "4.1" },
    { id: 3, name: "grilled", image: "https://hips.hearstapps.com/hmg-prod/images/delish-grilled-potatoes-jpg-1526061594.jpg", rating: 4.8 },
    { id: 4, name: "mashed", image: "https://images-gmi-pmc.edge-generalmills.com/1156f4ec-29c8-4cd9-80db-7d4ee330b1d0.jpg", rating: 4.0 },
];

function App() {
    return <div>{kinds.map(kind => {
        return (<Potato key={kind.id} fav={kind.name} image={kind.image} rating={kind.rating} />);
    })}</div>;

(2) jsx

jsx는 html 태그와 비슷한 형식을 띈다. 위 첫번째 src/App.js 에서
<Potato></Potato>로 표현한 게 jsx로, 여기에 (3)에서 설명하는 props를 속성으로 넣을 수 있다.

(3) props and proptypes

props는 (2)에서 설명한 태그 비슷한 것인 "jsx"의 속성으로 들어가게 되는 것이다.

import React from "react";
import PropTypes from "prop-types";
// import Potato from "./Potato";

function Potato({ fav, image, rating }) {
    return (
        <h4>
            I am talking Potato...
            <br></br>
            with {fav}
            <br></br>
            score: {rating}
            <br></br>
            which looks like this
            <br></br>
            <img src={image} width="200" height="100" alt={fav}></img>
        </h4>
    );
}

Potato.prototypes = {
    fav: PropTypes.string.isRequired,
    image: PropTypes.string.isRequired,
    rating: PropTypes.number,
};

const kinds = [
    { id: 1, name: "cheese", image: "https://i.ytimg.com/vi/2WU59bSygeA/maxresdefault.jpg", rating: 4.3 },
    { id: 2, name: "kimchi", image: "https://recipe1.ezmember.co.kr/cache/recipe/2015/04/18/41ff68622521fa4abaed787c4c8eafb31.jpg", rating: "4.1" },
    { id: 3, name: "grilled", image: "https://hips.hearstapps.com/hmg-prod/images/delish-grilled-potatoes-jpg-1526061594.jpg", rating: 4.8 },
    { id: 4, name: "mashed", image: "https://images-gmi-pmc.edge-generalmills.com/1156f4ec-29c8-4cd9-80db-7d4ee330b1d0.jpg", rating: 4.0 },
];

// 위 2번째 src/App.js랑 다른 점: renderKind를 arrowFunction 대신에 써서 jsx를 return 해 줌.
function renderKind(kind) {
    return <Potato key={kind.id} fav={kind.name} image={kind.image} rating={kind.rating} />;
}

function App() {
    return <div>{kinds.map(renderKind)}</div>;
}

export default App;

먼저, javascript를 쓰기 위해서는 {}를 이용한다고 한다. 그래서 div 안에 {}가 있고 그 안에 js 코드가 쓰여져 있는 것이고, map 함수의 경우 그냥 배열의 원소가 map 속의 함수에 각각 들어가 다른 output으로 다른 배열을 이루고 그걸 return한다고 보면 된다.
그래서 Potato를 불러주었으니 그 안의 props인 fac, image, rating이 들어가게 된다. 물론 이것들은 배열 kinds의 object의 속성들이고, 이것들이 props로 들어가게 되는 개념으로 나는 이해했다(이건 추가 리서치 필요)
props는 인자로 받을 때도 그렇고 function Potato안에 쓰일 때도 그렇고 {중괄호}로 쓰인다. 또한

function renderKind(kind) {
    return <Potato key={kind.id} fav={kind.name} image={kind.image} rating={kind.rating} />;
}

여기에서도 {중괄호}로 쓰인다. 이것 관련한 건 더 찾아보자.

proptypes는 npm i prop-types로 다운받은 것인데, 이걸로는 function Potato가 제대로 된 props를 받는 지를 체크할 수 있다고 한다.
그래서 PropTypes.string.isRequired이면 string이 아닌 다른 타입이 들어오면 에러를 나타낸다.

profile
이것저것 개발하는 것 좋아하지만 서버 개발이 제일 좋더라구요..

0개의 댓글