11.0 Class Components and State

2022. 9. 22. 15:17React/ReactJS로 영화 웹 서비스 만들기

자 그럼 이번에는 Class Component로 만들어보자~!

 

다 지우고, 다음과 같이 나타내보자.

우리가 매번 component를 만들 때마다 모든것을 구현하고싶지 않기 때문에,

exteds를 하였다.~!

그래서 우리의 App component는 react component다.

react component는 function이 아니기 때문에 return 을 가지고 있지 않다.

render method를 가지고있고, 이 App component안에 있다.

왜냐하면 react component에서 확장했기 때문에!

react component가 render method를 가지고 있어서, extend from 을 했기 때문에 이제 render method가 있다!!!

 

보다시피 class component와 function component는 차이가 존재한다.

function component는 function이고 뭔가를 return한다. 그리고 screen에 표시되고

class component는 class인데, react component로부터 확장되고, screen에 표시된다. 그리고 render method에 넣어야한다!

 

react는 자동적으로 모든 class component의 render method를 실행하고자 한다!

 

function component가 쉬운데 왜 class component를 이야기해야하나?

 

class component는 우리가 원하는 state때문에!

state는 object이고, component의 data를 넣을 공간이 있고 이 데이터는 변한다!

 

자 그럼 counter를 만들어보자~!

 

먼저 state를 만들어주고, state는 아래와 같이 쓴다.

 

그럼 javascript로 버튼을 만들어보자.

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

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

export default App;

그럼 다음과 같이 정상적으로 출력되는 것을 확인할 수 있다.

 

'React > ReactJS로 영화 웹 서비스 만들기' 카테고리의 다른 글

11.2 Component Life Cycle  (0) 2022.09.22
11.1 All you need to know about State  (2) 2022.09.22
10.4 Protection with PropTypes  (0) 2022.09.22
10.3 map Recap  (0) 2022.09.22
10.2 Dynamic Component Generation  (0) 2022.09.22