본문 바로가기
JavaScript/React

[React] #3.0 Class Components and State (#코딩공부)

by 함께 공부해요 2020. 5. 23.

https://youtu.be/rEazMgq2D8M


<복습>

https://wook-2124.tistory.com/131

 

[React] #2.4 Protection with PropTypes (#코딩공부)

https://youtu.be/JZhSIj8hgLE <복습> https://wook-2124.tistory.com/130 [React] #2.3 .map Recap (#코딩공부) https://youtu.be/icuG1Xk420g <복습> https://wook-2124.tistory.com/129 [React] #2.2 Dynamic C..

wook-2124.tistory.com

 

<준비물>

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com

ko.reactjs.org/docs/state-and-lifecycle.html

 

State and Lifecycle – React

A JavaScript library for building user interfaces

ko.reactjs.org


1. class component

class component는 function component와는 다르게 state(상태)를 표현할 수 있다. class App extends React Component의 의미는 React Component로 부터 App을 확장시켰다는 뜻인데, baby가 human에서 확장된 것과 비슷한 맥락이다. React Component는 많은 method를 갖고 있고 그중에 State가 있다.

 

function이 아닌 class로 지정한 component이기 때문에 return이 바로 되지 않는다. 때문에 원래 React Component의 method인 render를 extends해서 받아왔으니 그대로 쓰고, 다음으로 표현할 것들을 return해서 표현했다.

 

즉, function component와 class component의 차이점function은 함수로써 바로 뭔갈 return하고 screen에 표현하지만, class는 React Component를 extends하고 render(표현) method로 return을 적어서 표현해야된다.


2. state

function component가 아닌 class component를 사용하는 이유는 React Component의 method인 state 때문인데, state는 하나의 object(객체)라고 생각하면 된다.

 

state(상태)는 dynamic date(유동적인 데이터)이다. 즉, 변하는 데이터 혹은 존재하지 않는 데이터라고 칭할 수 있다. 보통 시계 기능이나, 변화를 주고 싶은 data를 state로 정한다. 그리고 class에서 쓸 때는 { }에 this object에 state를 붙여서 불러준다.

 

class component의 state로 정한 count data를 바꾸기 위한 작업을 위해 Add와 Minus button을 추가했다. 그리고 이렇게 적은 코드는 React 코드가 아닌 JavaScript 코드이다. 때문에 React JS라고도 불린다.

 

state(상태) 밑으로 add와 minus fucntion = () 버튼이라고 정의하고 가시적으로도 보기 위해서 console로 출력했다. onClick은 React에 있는 prop 기능이고 JavaScript 였다면 addEventListener로 event에 대한 반응을 해주면 된다. 그리고 this.state.count와 같이 this는 class component이기 때문에 object앞에 붙여서 써줬다.

 

이렇게 Add, Minus button를 onClick했을 때 반응하는 것까지 console로 출력해봤다.

 

다음 시간에는 Add, Minus button을 눌렀을 때 각 button에 반응해서 state의 count를 자동으로 업데이트 하는 것을 해보겠다.

 

ko.reactjs.org/docs/state-and-lifecycle.html

 

State and Lifecycle – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

댓글