Class Components and State

이재진·2021년 4월 26일
0

Class Component와 function Component의 차이

function Component는 function. 무언가를 return 한다. 그리고 스크린에 표시된다.
Class Component는 class. 하지만 React Component로 부터 확장되고 나서 스크린에 표시된다.
(그것을 render method에 넣어야만 한다.)

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

class App extends React.Component {
  render() {
    return <h1>나는 클래스 컴포넌트야.</h1>;
  }
}

export default App;


리액트는 자동적으로 모든 Class Component의 render method를 실행하고자 한다.

class App extends React.Component {
  state = {
    count: 0, //내가 바꿀 데이터를 state에 넣는다
  };
  render() {
    return <h1>The number is {this.state.count}.</h1>;
  }
}

state에는 바꾸고 싶은 data를 넣는 것이다.

class App extends React.Component {
  state = {
    count: 0, //내가 바꿀 데이터를 state에 넣는다
  };

  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>
    );
  }
}

자바스크립트에는 다른 onClick이나 이벤트리스너를 등록해야 하지만 리액트에는 자동적으로 주어진 onClick 을 가지고 있다.

<button onClick={this.minus} 에서
this.minus()로 쓰면 안된다. 즉시 호출이 아니다. 클릭했을 때만 함수가 호출되길 원하기 때문이다.

profile
개발블로그

0개의 댓글