React 기초 (4) : Class Component & State

shelly·2021년 6월 9일
0

React

목록 보기
4/10

1. Class Component

function component

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

function App () {
  return <div></div> 
}

export default App;

class component

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

class App extends React.Component { // --- (1)
  state = {
    count: 0 // --- (2)
  }
  render() { // --- (3)
    return <div> The number is : {this.state.count}</div>
  }
}

export default App;
  • (1) react class component를 만들기 위해서 React.component상속받는다.
  • (2) Class componentstate갖는다. 반면, Function componentstate갖지 않는다.
  • (3) React.Component로부터 상속받은 render함수를 사용하여 HTML element를 반환한다.

2. State

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

class App extends React.Component {
  state = {
    count: 0
  }

  add = () => {
    this.setState({ count : this.state.count + 1}) // --- (1)
  } 

  minus = () => {
    // this.setState({count : this.state.count - 1})

    this.setState(current => ({ count : current.count - 1 })) // --- (2)
  } 

  render() {
    return (
      <div>
        <h1>The number is {this.state.count}</h1>
        <button onClick={this.add}>ADD</button> // --- (3)
        <button onClick={this.minus}>MINUS</button>
      </div>
    )
  }
}

export default App;
  • ADD 버튼을 누르면 count가 1 증가하고, MINUS 버튼을 누르면 count가 1 감소한다.
  • (1) this.state.count += 1과 같이 코드를 작성하면 count값은 변할지라도, 화면에 반영이 되지 않는다. setState를 사용하여 count 값을 변경하면, 다시 render되기 때문에 변경된 count값이 화면에 나타난다.
  • (2) 이와 같은 형태로 setState를 사용할 수 있다.
  • (3) click eventonClick이다. 코드 컴파일시 즉시 실행이 아니라, 클릭 시 발생하는 함수이기 때문에 this.add()가 아닌, this.add로 코드를 작성한다.

0개의 댓글