본문 바로가기
React

[React] Class Components and State

by 꿈나무 김땡땡 2020. 7. 27.
  • dynamic data : 변하는 데이터
  • state : object. 바꾸고 싶은 데이터를 state 안에 넣는다.
  1. function App() --> class App extends React.Component로 변경 (function component --> class component)
    1. React.Component는 return이 없고 render method가 있음
    2. render method에서 return 실행
    3. Class component는 render method 자동 실행
    4. class component는 state를 가지고 있기 때문에, function component가 아닌 class component 사용
  2. state를 선언하고 render()에서 {this.state.count} 형식으로 구현
    1. React는 onClick method 있으므로 onClick으로 바로 구현 가능
    2. onClick = {this.add}는 클릭할 때 더하는 역할
    3. this.add() : 즉시 더한다. <-> this.add : 클릭이 발생할 때 더한다.

코드

import React from 'react';
import PropTypes from "prop-types";

function Food({name, picture, rating}) {
  return <div>
    <h2>I like {name}</h2>
    <h4> {rating} / 5.0 </h4>
    <img src={picture} alt={name}/>
  </div>
}

// propTypes 추가
Food.propTypes = {
  name: PropTypes.string.isRequired,
  picture: PropTypes.string.isRequired,
  rating: PropTypes.number
}

class App extends React.Component {
  state = {
    count: 0
  }
  add = () => {
    console.log("add");
  };
  minus = () => {
    console.log("minus");
  };
  render() {
    return <div>
      <h1>The number is : {this.state.count}</h1>
      <button onClick={this.add}>Add</button> 
      <button onClick={this.minus}>Minus</button>
    </div>; // state 불러오기
  }
}


export default App;

https://github.com/grace-kimm/movie_app_2020/commit/aa83cc4198bae548e26103184752d9340ebbce45

 

#3.0 Class Components and State · grace-kimm/movie_app_2020@aa83cc4

Permalink Browse files #3.0 Class Components and State Loading branch information Showing 1 changed file with 18 additions and 45 deletions. +18 −45 src/App.js @@ -16,51 +16,24 @@ Food.propTypes = { rating: PropTypes.number } const foodILike =[ { id: 1,

github.com

 

출처

https://nomadcoders.co/react-fundamentals/lectures/1552

 

All Courses – Nomad Coders

초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!

nomadcoders.co

 

댓글