본문 바로가기
Front-End/React

[React] React에서 this는 무엇인가?

by SeanK 2021. 12. 5.

 

 

코딩 초급자 입장에서 this란 개념은

 

아무리 공부해도 새로운 느낌이다...

 

역시나 React에서도 this는 어김없이 등장하는데, 

 

오늘은 다시 한번 this에 대해 이해하는 시간을 가져보려고 한다. 

 

사실 이건 javascript 카테고리 안에 작성해야 하는 글이나, React를 공부하는 도중 학습한 내용이므로

 

React 카테고리에 글을 올린다. 

 

마찬가지로 관련해서 자세한 설명이 있는 글이 있어 번역하여 옮겨본다:

 

출처: https://medium.com/byte-sized-react/what-is-this-in-react-25c62c31480

 

What is ‘this’ in React?

And why do we use it all the time?

medium.com

 

What is ‘this’ in React?

 
만약 React에 뛰어들었다면 아마 엄청나게 많은 this를 보고 있을 것이다. 자바스크립트와 리엑트에서 this 키워드가 의미하는 바가 무었인지 한번 깊숙히 들어가 보자. 
 
 

The 'this' keyword

this 카워드는 기본적으로 사용된 스코프나 문맥에 따라 자바스크립트 엘리먼트를 참조한다. 몇 가지 예를 아래와 같이 설명해 보겠다. 

 

Global 'this' scope

가장 기본적인 스코프는 웹브라우저의 글로벌 스코프다. 웹의 콘솔 창을 열고 아래와 같이 입력해보자. 

this

 웹브라우저는 global Window 객체를 반환할 것이다. 

Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, …}

Window 객체에서 실행할 어떠한 명령문도 this 글로벌 스코프로 실행할 수 있다. 

this.alert(‘Hey!’)
//Is the same as
Window.alert(‘Hey!’)this.location = ‘https://medium.com'
//Is the same as
Window.location = ‘https://medium.com'

 

Function 'this' scope

 

이부분에서 this가 약간 혼란스러워진다. 그리고 이를 이해하기 위해 lexical scope에 대해 알고 있어야 한다. 

 

자바스크립트 함수에서 this의 값은 어떻게 함수가 불리는지에 따라 결정된다. call, apply, 그리고 bind 메소드는 명백하게 함수 내의 this 값을 설정한다. 하지만 만약 이 this의 값이 명백하게 설정되지 않는다면, this 값은 디폴트 값으로 global context로 맞춰진다. 

 

const thisFunction = function () {
return this;
}
//Calling thisFunction() in the browser will return the window object

 

Strict 모드를 사용하면, this 값은 명백한 값을 참조하거나, 명백하게 값이 설정되지 않았을 경우 undefined로 this 값이 설정된다. 

 

const strictFunction = function() {
 ‘use strict’;
 return this;
}
//Calling strictFunction() in the browser will return undefined since this is not explicitly set with call, apply, or bind

 

Explicitly setting 'this' with call, apply, bind, and the arrow function

 

그렇다면 어떻게 명백하게 this값을 함수내에서 설정할 수 있을까? call, apply, 그리고 bind 메소드가 이를 해결해 준다. 

 

함수 내에서 call 메소드는 객체를 받는데, 'this'이 객체를 참조하고 함수에서 정의된 다른 파라미터를 참조할 것임을 뜻한다. apply 메소드는 객체를 받고 'this'는이 객체를 참조하고 함수에서 정의된 다른 파라미터를 참조할 것을 뜻한다.

 

const object = {
 a: 5,
 b: 7
}const thisFunction = function(c, d) {
 return this.a + this.b + c + d;
}thisFunction.call(object, 12, 4);
//will return 28thisFunction.apply(object, [3, 6]);
//will return 21

 

bind 메소드는 객체 하나를 함수에 첨부해 매번 함수가 호출될 때 바운딩된 객체를 참조한다는 점에서 call과 apply와는 다르다.

 

const object = {a: 2, b:3, c:6};const thisFunction = function() {
 return this.a + this.b + this.c;
}const bindFunction = thisFunction.bind(object);bindFunction(); //will return 11

 

Object context

 

객체 안에서 this를 사용 할 때, this는 객체 자기 자신을 참조한다. 이는 객체 메소드에서 객체의 값을 참조하기 쉽게 해 준다. 

 

const object = {
 a: 2,
 b: 3,
 thisFunction: function(){
 return this.a + this.b;
 }
};object.thisFunction() //returns 5

 

 

So what does this mean for React

 

React 클래스 컴포넌트에서 우리는 메소드가 props와 state와 같이 클래스 특성을 참조할 것이라고 정의한다. 그러나 메소드가 this.props 혹은 this.state에 접근하도록 하려면 React 컴포넌트 this context를 해당 메소드로 바인딩할 필요가 있다. 

 

import React, { Component } from ‘react’;class App extends Component {
  constructor(props) {
    super(props);
    this.clickFunction = this.clickFunction.bind(this);
  }  clickFunction() {
    console.log(this.props.value);
  }  render() {
    return(
      <div onClick={this.clickFunction}>Click Me!</div>
    );
  }
}

 

클래스 메소드로 this를 바인딩하면 컴포넌트의 props와 state에 this.props와 this.state로 접근이 가능해진다. 

 

 

The Arrow Function

눈치 챌 수 있듯이 this를 클래스 메소드로 바인딩하는 것은 수많은 boiler plate를 발생시킨다. ES6에는 화살표 함수가 소개되었는데 화살표 함수에서는 this context가 함수에 이미 바인딩되어 있다. 이러한 멋진 기능 덕분에 우리는 public class fields를 자동적으로 메소드에 바인딩할 수 있다. 

 

const myFunction = () => {
 return this.props.a + this.props.b;
}//The previous stated myFunction is the same as...const myFunction = function() {
  return this.props.a + this.props.b;
}.bind(this);

 

화살표 함수와 public class filed의 혼합은 깨끗하고 선언적인 방식으로 react 컴포넌트를 정의할 수 있도록 개선시켰다. 

 

 

 

'Front-End > React' 카테고리의 다른 글

[React] Presentational vs Container Component  (0) 2021.12.10
[React] State값을 직접변경하면 안되는 이유  (0) 2021.12.10
[React] React의 세가지 특성  (0) 2021.12.05
React Debounce개념  (0) 2021.11.21
React Throttle 개념  (0) 2021.11.21