이벤트 bind 함수 이해하기

SPANKEEE·2022년 11월 22일
0

리액트-시작

목록 보기
15/30

이전 글에는 }.bind(this)를 추가 했었다.
이 코드는 무슨 뜻일까?

bind

bind()함수란
이전에 render()함수가 호출될 때 render()함수 안에서 console.log('render', this);를 실행시켜보자.

App.render()마지막 구간

console.log('render', this);

결과

  • render() 함수 안에서 console.log('render', this) 여기 this컴포넌트 자신을 가리킨다.

그리고 <header> 안에 이전에 짰던 코드를 주석처리 하거나 return을 입력시켜
다음과 같은 코드를 위에 추가한다.

<App> render() -> <header> 영역

  • onClick 안에 익명함수가 끝날때 .bind(this)를 잠시 지워보자.
<header>
  <h1>
    <a href='/' onClick={function (e) {
      console.log('event in', this);
      e.preventDefault(); // a 태그의 동작을 금지함
      return;
      console.log(e); // 이벤트 매개변수 e 출력
      // state mode 변경
      this.setState({
        mode: 'welcome'
      });
    }}>{this.state.subject.title}
    </a>
  </h1>
  {this.state.subject.sub}
</header>

결과
event in undefined

bind(this)를 제거했더니 정의되지 않음으로 확인할 수 있다.

이때 event inundefined이므로...

render라고 하는 함수 안에서 this는 이 render 함수가 속해 있는 컴포넌트 자체를 가리키는데,

onClick안의 익명 함수는 이상하게 this가 아무 값도 가지고 있지 않다.

this를 주입하는 방법

익명 함수this값이 없을 때 강제로 this를 주입하는 방법을 알아보자.

그 전에 bind()라는 함수가 무엇인지 알아보자.

console

var obj = {name : 'kim'};
// this값 목표
function bindTest(){
	console.log(this.name);
}
// this값 콘솔로그로 출력
bindTest();
// 함수 실행

>> undefined

  • name은 kim이란 값이 있는 객체를 만들고 bindTest()함수를 호출했을 때 this의 값을 obj로 설정하려고 한다.
  • 하지만 bindTest()함수를 실행하게 되면 undefined가 출력된다.
  • this는 지금 obj가 될 이유가 전혀 없기 때문

이번엔 bindTest()라는 함수에 bind()라고 하는 함수를 다시 호출해 보자.

그리고 저 bind()함수에 인자로 obj를 부여를 해본다.

consle

// 선언
var bindTest2 = bindTest.bind(obj);
// 실행
bindTest2();

>>kim

  • bind()함수로 인해서 bindTest()함수의 블록 안에서 thisobj가 된다.
  • 즉 우리가 원하는 동작을 수행하는 bindTest2()라는 새로운 함수가 만들어 진다.
  • bindTest2()라는 함수 내부에서 this의 값이 obj가 됐기 때문에 bindTest2()함수를 실행시키면 "kim"이 출력된다.

bind() 요약

  • bind()라고 하는 함수가 하는 일은 우리 코드에서 onClick 이벤트bind(this)를 실행하면..?
  • <App>컴포넌트 자체를 가르키는 객체를 함수 안으로 주입해서 이 함수 안에서 this는 그 객체가 되게 하는 것이다.
profile
해야되요

0개의 댓글