화살표함수와 this와 React

KHW·2021년 11월 12일

유튜브강의

목록 보기
7/9

bind의 역할

바인드하는 함수에서 사용하는 this의 대상을 지정해주는 역할이다.

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

const objB = {
  name: 'b',
}

objA.aFunc() // (1)
// a
objA.aFunc.bind(objB) // (2)
const foo = objA.aFunc.bind(objB) // (3)
foo()
  • objA.aFunc 메서드에서 사용하는 this는 objB로 처리가 된다.
    이를 통해 foo()를 실행하면 a가 아닌 b가 나온다.

React 에서의 bind()

import React from 'react'

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

버튼 클릭시
BindTest {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternals: FiberNode, …} 출력


import React from 'react'

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

버튼 클릭시
undefined 출력

this

자바스크립트의 this 는 실행시의 context

this가 전역객체일때

const thisTest = function() {
  console.log(this.value)
}
thisTest.value = 'I am this'
thisTest()	//undefined

thisTest()가 출력될 때의 context 가 전역객체이기 때문

this가 thisTest일때

const thisTest = function() {
  console.log(this.value)
}
thisTest.value = 'I am this'
thisTest.func = function() {
  console.log(this.value)
}
thisTest.func()		// I am this

thisTest.func()가 출력될 때의 context 가 thisTest이기 때문

React에서의 this

나는 4가지경우를 통해 this를 시도해보았다.

import React from "react";

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

  otherFunc() {
    console.log(this);
    this.handleClick();
  }
  render() {
    return (
      <div>
      	//1
        <button
          type="button"
          onClick={() => {
            this.handleClick();
          }}
        >
          Goodbye bind
        </button>

	//2
        <button type="button" onClick={this.handleClick}>
          Goodbye bind
        </button>

	//3
        <button
          type="button"
          onClick={() => {
            this.otherFunc();
          }}
        >
          Goodbye bind
        </button>

	//4
        <button type="button" onClick={this.otherFunc}>
          Goodbye bind
        </button>
      </div>
    );
  }
}
export default BindTest;
  • 총 4개의 버튼이 있다.

첫번째 버튼

BindTest가 this인 채로 출력된다.

두번째 버튼

실행되는 문맥이 바로 전역(window)객체라서 undefined가 출력

세번째 버튼

otherFunc()로 this가 출력되고 this.handleClick();를 실행시켜 다시 this가 BindTest가 출력

네번째 버튼

otherFunc()에서 this는 undefined로 뜨고 이를 통해
접근하려는 this.handleClick();에서 에러가 뜬다.

해결하기

간단히 화살표함수로 쓰면 전부 같은 결과의 this를 처리한다.

출처

링크

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글