React - Class Component에서 this란?

김정인·2023년 1월 2일
0

React

목록 보기
1/4

연관 글
JS - this란?


📌React Class Component에서 this


리액트 클래스 컴포넌트는 state, props, 컴포넌트에 선언한 메서드 등을 참조하기 위해 this를 사용하고 있음을 직관적으로 확인할 수 있으며 따라서 코드를 작성할 때 this를 신경써야 합니다.

컴포넌트 안에서 this로 참조할 수 있는 프로퍼티

  • state
  • props
  • refs
  • 컴포넌트 메서드
  • 생명주기 메서드

🔎 생명주기 메서드의 this

import React from "react";

class App extends React.Component {

  // 컴포넌트 안 메서드 선언
  componentMethod(){
    console.log("method called !! method의 this는", this); //App 컴포넌트
  };

  componentDidMount() {
    console.log('componentDidMount Called !! componentDidMount()의 this는', this); //App 컴포넌트
    this.componentMethod(); // 메서드 호출
  }

 render() {
  console.log('render Called !! render()의 this는', this); //App 컴포넌트
  
    return (
      <div>
        <h1>Class Component this</h1>
      </div>
      );
    }
  }

export default App;

  • 생명주기 메서드의 this는 메서드를 호출한 해당 컴포넌트를 가리킵니다.

  • 따라서 컴포넌트안에 선언한 다른 메서드들도 생명주기 메서드 안에서 this로 호출 가능합니다.


🔎 생명주기 메서드의 this


컴포넌트에서 선언한 메서드들은 기본적으로 해당 컴포넌트를 this로 바인딩하고 있습니다. 하지만

JSX 이벤트 핸들러의 콜백 함수로 컴포넌트에서 선언한 메서드를 전달할 때 예외케이스가 발생합니다.

import React from "react";

class App extends React.Component {
  
  // 상태값 num 선언
  state = {
    num: 0,
  };

  // 버튼을 누르면 this.state.num을 1만큼 증가시킴
  increase() {
    console.log('increase메서드의 this는', this);
    
    this.setState((current) => ({ num: current.num + 1 }));
  }

  render() {
    return (
      <div>
        <h2>{this.state.num}</h2>
        {/* 클릭 이벤트 핸들러의 콜백으로 컴포넌트 메서드 전달 */}
        <button onClick={this.increase}>증가</button>
      </div>
    );
  }
}

export default App;

  • 위와 같이 증가라는 버튼에 이벤트로 this.increase 메서드를 호출했으나, this.setState is not a function 에러가 발생가 발생하는 것을 확인할 수 있습니다.

그 이유는 메서드가 실행될 때 바인딩된 this로 setState() 함수를 참조할 수 없기 때문인데, 이는 일반적으로 onClick={this.increase} 과 같이 뒤에 ()를 사용하지 않고 메서드를 참조할 경우 해당 메서드를 바인딩 해야하기 때문입니다.


  • 해결방법 1. bind()

    • func.bind(thisArg[, arg1[, arg2[, ...]]]) 함수는 넘겨받은 this 및 인자들을 바탕으로 새로운 함수를 리턴합니다.

    • Constructor()에 작성하거나, 이벤트 핸들러의 인자로 bind()를 호출한 메서드를 넘깁니다.

ex)

<button onClick={this.increase.bind(this)}>증가</button>

  • 해결방법 2. 화살표 함수

    • 화살표 함수는 다른 함수와 달리 따로 this를 가지고 있지 않고, 항상 상위 스코프의 this에 바인딩 합니다.( lexical this )

    • 넘긴 화살표 함수는 상위 스코프인 render() 메서드의 this인 컴포넌트(여기서 App)를 바인딩합니다.

ex)

<button onClick={() => this.increase()}>증가</button>

🔎 함수형 컴포넌트에서 this는 ?..

함수형 컴포넌트 자체와 함수형 컴포넌트 안에서 선언한 함수들 모두 전역 객체를 this로 가지고 있기 때문에 애초에 this가 모두 다 같습니다. 따라서 이벤트 핸들러에 콜백 함수를 넘기는 상황에도 신경 쓸 필요가 없습니다.


🔗 참고한 글

React 컴포넌트와 this

profile
FE 개발자

0개의 댓글