본문 바로가기
1st life_Programmer/React

[React] Binding 바인딩

by Z선배 2019. 7. 26.

 

우선, 리액트에서의 바인딩을 알아보기 전에 자바스크립트에서 "this"에 대한 이해가 되어있어야 리액트에서의 바인딩을 알 수 있습니다.

 

  • 자바스크립트 바인딩

     

    객체안의 메서드에서 this는 그 메서드가 포함된 object를 가리키게 됩니다.

     

var obj = {  
    prop: 'Hello',
    sayHello: function() {
        console.log( this.prop );
    }
};
 
// 1.
obj.sayHello(); //"Hello"
// 2.
var reference = obj.sayHello;
reference(); // undefined
  1. sayHello 메서드안의 this는 obj객체가 되어 obj.prop인 Hello를 전달받아 콘솔 로그를 출력합니다.

  2. 변수 reference에 담길 때 obj와의 관계가 상실되어 정의할 수 없는 상태가 됩니다.

     

    > 이 때 필요한 것이 바인딩 이다!

     

var reference = obj.sayHello.bind(obj);
reference(); // "Hello"

그렇다면 조금 더 심화된 예제를 살펴보겠습니다.

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

const objB = {
  name: 'b',
}

// 1.
objA.aFunc() // a

// 2.
objA.aFunc.bind(objB)
const foo = objA.aFunc.bind(objB) 
foo() // b

bind() 함수를 다시 설명하자면 바인드하는 함수에서 사용하는 this의 대상을 지정해주는 역할을 합니다.

즉, bind함수를 사용하는 객체의 this를 ()안의 객체로 바꾸어 준다는 말입니다.

objA.bind(objB) == objA안에 있는 this를 objB라고 정의한다. 라는 말이지요!

  1. objA의 aFunc함수를 실행하면 예상대로 a가 출력됩니다.

  2.  

    여기서는 objA이 aFunc함수의 this가 objB라고 정해줬으므로 b를 출력하게 됩니다.

     

     


  • 리액트 바인딩

    리액트에서 컴포넌트에 이벤트 메서드를 연결하는 방법(바인딩)

    예전에 클래스 컴포넌트에서는 생성자에서 바인딩을 해줄 수 있었지만

    현재는 화살표 함수(arrow function)을 사용하자는 추세입니다.

    arrow function은 this를 자동으로 bind해주기 때문에 따로 bind함수를 작성하지 않아도 됩니다.

     

     

  • 일반 함수

     

import React, { Component } from 'react';

class Basic extends Component {
  constructor(props) {
    super(props);
    this.onClickButton = this.onClickButton.bind(this);
  }

  onClickButton() {
    console.log('ok');
  }

  render() {
    return (
      <button onclick={this.onClickButton}>버튼</button>
    );
  }
};

export default Basic;
  • arrow function

import React, { Component } from 'react';

class Basic extends Component {
  constructor(props) {
    super(props);
    // this.onClickButton = this.onClickButton.bind(this); 생략 가능
  }

  onClickButton = () => { // 함수를 arrow function방식으로 작성
    console.log('ok');
  }

  render() {
    return (
      <button onclick={this.onClickButton}>버튼</button>
    );
  }
};

export default Basic;

 

 

※ 이 포스팅은 아래의 글들을 참조해서 작성하였습니다.

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

https://jeong-pro.tistory.com/79

https://kimch3617.tistory.com/entry/React-%ED%95%A8%EC%88%98-bind-%EC%83%9D%EB%9E%B5%ED%95%98%EA%B8%B0

댓글