Web 강의/ReactJS로 영화 웹 서비스 만들기

[노마드코더/ReactJS로 영화 웹 서비스 만들기]3.0 Class Components and State

sumiin 2022. 3. 18. 16:53
반응형
SMALL

#3.0 Class Components and State

  • state 는 보통 우리가 동적데이터와 함께 작업할 떄 만들어짐
  • class component와 function component 차이

  • function component

    • function이고 뭔가를 return 하고 screen에 표시
  • class component

    • class이지만 react component로부터 확장되고 screen에 표시되며 render method안에 넣어야함
    • react는 자동적으로 모든 class component의 render method를 실행하고자 함
    • state를 가지고 있음
  • state

    • object
    • component의 data를 넣을 공간이 있고 그 data는 변함 (state를 사용하는 이유)
  • class App extends React.Component

    • component를 만들때마다 모든 것을 다 구현하지 않기 위해 extend from 사용
    • class React component는 function 이 아니기 때문에 return 을 가지고 있지 않음
    • render method를 가지고 있음
    • state={count:0}; 형식으로 표현
    • state를 render에 사용하고 싶을 경우, {this.state.count} 형식으로 표현

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>
    );
  } 
}
//()는 즉시 나타내는 함수이기 떄문에 onClick에서는 this.add()가 아닌 this.add를 써서 버튼을 클릭했을 때만 나타나게 함
export default App;
반응형
LIST