Language/React.js

[React] JavaScript / React Binding

마탁이 2021. 1. 24. 21:23

blueshw.github.io/2017/07/01/arrow-function/

 

[ES6, react] 리액트에서 화살표 함수(arrow function)는 선택이 아닌 필수

리액트를 개발하다보면 이런 코드를 본적 있을것입니다. this(아마도 react 클래스 객체)에 속한 어떤 메서드를 다시 this 에 bind 한다라?? 굳이 왜 이런짓을 해야하는지 의문이 들만합니다. 리액트

blueshw.github.io

- 위 페이지가 정리 및 이해가 잘되어 참조하여 학습하였다.

 

1. this

 - 객체지향 언어에서의 일반적인 this의 의미 : 현재 객체를 지칭

   JavaScript의 this : 실행시의 context

 - 아래의 예에서는 'undefined' 가 콘솔에 출력된다.

   Hello()가 출력될 때 context가 전역객체이기 때문이다.

   Hello.value는 Hello의 속성인데 전역객체에서 value를 찾고 있어 'undefined'를 출력한다.

const Hello = function() {
    console.log(this.value);
}

Hello.value = 'Hello'
Hello();

 

 - 아래의 예제에서는 Hello를 출력할 수 있다.

   Hello 객체의 func()를 호출하면 이 때는 this가 Hello가 되기 때문에 this.value를 가져와 출력할 수 있다.

const Hello = function() {
    console.log(this.value);
}

Hello.value = 'Hello'
Hello.func = function() {
    console.log(this.value);
}
Hello.func();

2. bind()

 - bind하는 함수에서 사용하는 'this'의 대상을 지정해주는 역할.

const objectA = {
    name:'a',
    aFunc : function() {
        console.log(this.name);
    }
}

const objectB = {
    name:'b',
}

objectA.aFunc();

/**
 * objectA.aFunc.bind(objectB);
 * -> aFunc와 동일한 기능을 하는 새로운 함수를 만들며
 * aFunc의 this는 objectB가 된다. 
 * */ 
const isBprint = objectA.aFunc.bind(objectB);
isBprint()

 

3. React의 this

 - 아래의 예에서 render() 함수를 참조한다.

   컴포넌트의 render() 함수가 실행되면 DOM이 그려진다.

   이 때, this는 WithoutBindTest객체를 가리키지만

    handleClick() 함수가 호출될 때는 this가 전역객체(Window)를 의미한다.

    왜냐하면 this 라는 값은 호출하는 문맥(context)에 의해 결정되는데, 클릭이 실해오디는 문맥이 전역객체이다.

import React from 'react';
import ReactDOM from 'react-dom';

class WithoutBindTest extends React.Component {
  handleClick() {
    console.log(this);
  }
  render() {
    return (
      <button type="button" onClick={this.handleClick}>
        Goodbye bind without this
      </button>
    );
  }
}

ReactDOM.render(<WithoutBindTest/>, document.getElementById('root'));

 

4. Arrow Function

 - click, change 등의 이벤트 리스너를 사용할 때마다 bind()함수를 작성하는 것 보다는

   ES6에서는 Arrow Func을 사용하면 아래와 같이 효율적으로 문제를 해결할 수 있다.

 - Arrow Func의 this는 외부함수(부모함수)의 this를 상속받기 때문에 this는 항상 일정하다.

import React from 'react';
import ReactDOM from 'react-dom';

class BindTest extends React.Component 
{
  handleClick = () => {
    console.log(this)
  }

  render() {
    return (
      <button type="button" onClick={this.handleClick}>
        Goodbye bind
      </button>
    )
  }
}

ReactDOM.render(<BindTest/>, document.getElementById('root'));

 

'Language > React.js' 카테고리의 다른 글

[React] React Hooks  (0) 2021.02.01
[React] NPM과 NPX, package-lock.json  (0) 2021.01.27
[React] React Event  (0) 2021.01.24
[React] React 수명주기(Lifecycle)  (0) 2021.01.24
[React] React State  (0) 2021.01.24