본문 바로가기
SeSAC

[SeSAC] React 학습 정리(3) / 이벤트-클래스형 컴포넌트

by hotdog7778 2023. 9. 28.

1. 함수를 선언해서 바로 onClick으로 전달 (일반, 화살표)

2. 메서드로 바꿔서 onClick에 전달

3. Bind를 써서 일반함수를 원하는대로 사용

4. 일반and화살표 이벤트 핸들러에게 인자를 전달하는 두가지 방법

 

 

React 클래스형 컴포넌트 이벤트 핸들링 (이벤트 핸들러의 this,  bind, 화살표함수, 인자 전달) 

 

1. 함수를 선언해서 바로 onClick으로 전달 (일반, 화살표)

 

* JavaScript에서 함수가 일반 함수로 호출될 때, 함수 내부에서의 this는 호출한 곳에 따라 달라짐.

* JavaScript에서 함수가 화살표 함수로 호출될 때, 함수 내부에서의 this는 정의된 곳의 바로 외부 범위임.

import { Component } from 'react';

class WhatIsThis extends Component {
  render() {
    return (
      <>
        <h1>이벤트 헨들러에서 this</h1>
        <button onClick={function () {console.log(this)}}>일반함수인 이벤트 핸들러 실행</button>        
        <button onClick={() => {console.log(this)}}>화살표함수인 이벤트 핸들러 실행</button>
      </>
    );
  }
}

export default WhatIsThis;

 

콘솔로그 출력 값

onClick에 화살표 함수를 전달할때 화살표 함수 내부의 this는 WhatIsThis 라는 컴포넌트 자체라는걸 확인.

onClick에 일반 함수를 전달하면 함수 내부의 this는 undefined.

 

 

2. 메서드로 바꿔서 onClick에 전달

import { Component } from 'react';

class WhatIsThis extends Component {
  normalFunc() {
    console.log('normalFunc 실행')
    console.log(this)
  }
  arrowFunc = () => {console.log(this)}
  
  render() {
    return (
      <>
        <h1>이벤트 핸들러에서 this</h1>
        <button onClick={this.normalFunc}>일반함수인 이벤트 핸들러 실행</button>        
        <button onClick={this.arrowFunc}>화살표함수인 이벤트 핸들러 실행</button>
      </>
    );
  }
}

export default WhatIsThis;

 

콘솔로그 출력 값

버튼 태그내에서 this는 컴포넌트 자체니까 메서드를 잘 찾아간다.

메서드 내부(일반 함수 형식) 의 this는 undefined

메서드 내부(화살표 함수 형식) 의 this는 컴포넌트 자체

 

 

3. Bind를 써서 일반함수를 원하는대로 사용

import { Component } from 'react';

class WhatIsThis extends Component {
  constructor() {
    super();
    // console.log("!!",this) // 생성자에서 this는 컴포넌트 자체임을 확인함
    this.normalFunc = this.normalFunc.bind(this);
  }
  
  normalFunc() {
    console.log('normalFunc 실행')
    console.log(this)
  }
  arrowFunc = () => {console.log(this)}
  
  render() {
    return (
      <>
        <h1>이벤트 핸들러에서 this</h1>
        <button onClick={this.normalFunc}>일반함수인 이벤트 핸들러 실행</button>        
        <button onClick={this.arrowFunc}>화살표함수인 이벤트 핸들러 실행</button>
      </>
    );
  }
}

export default WhatIsThis;

 

콘솔로그 출력 값 / 일반 함수의 this >&nbsp; 화살표 함수의 this 순서(위에서 아래)

normalFunc(일반함수로 정의된 메서드)에 bind를 사용해서 this를 명시해주면

화살표 함수와 동일하게 함수 내부의 this가 컨택스트 전체를 가리키게 할 수 있다.

 

 

4. 일반and화살표 이벤트 핸들러에게 인자를 전달하는 두가지 방법

 

방법1. bind

방법2. 화살표 함수

import { Component } from 'react';

class WhatIsThis extends Component {
  constructor() {
    super();
    // console.log("!!",this) // 생성자에서 this는 컴포넌트 자체임을 확인함
    this.normalFunc = this.normalFunc.bind(this);
  }
  
  normalFunc(msg) {
    console.log('normalFunc 실행')
    console.log(msg)
  }
  arrowFunc = (msg) => {console.log(msg)}
  
  render() {
    const msg = "하하"
    return (
      <>
        <h1>이벤트 핸들러에서 this</h1>
        {/* 이벤트 핸들러에 인자로 msg를 넘겨보기 */}
        
        {/* 방법1. 인자로 넘길 값을 bind 하는 방법 */}
        <button onClick={this.normalFunc.bind(null, msg)}>일반함수인 이벤트 핸들러에게 bind를 사용해서 인자 전달</button>
        <button onClick={this.arrowFunc.bind(null, msg)}>화살표함수인 이벤트 핸들러에게 bind를 사용해서 인자 전달</button>

        {/* 방법2. 인자로 넘길 값을 화살표 함수를 사용해서 처리 */}
        {/* 화살표 함수를 사용하면 this는 컴포넌트 자체 */}
        <button onClick={() => this.normalFunc(msg)}>일반함수인 이벤트 핸들러에게 화살표 함수를 사용해서 인자 전달</button>                
        <button onClick={() => this.arrowFunc(msg)}>화살표 함수인 이벤트 핸들러에게 화살표 함수를 사용해서 인자 전달</button>
      </>
    );
  }
}

export default WhatIsThis;

 

콘솔로그 출력값 / 방법1, 방법2 모두 인자로 msg를 받음

 

 

5. 화나네요 그냥 화살표 함수 쓰겠습니다.

 

-끝-

함수형 컴포넌트는 다음 포스팅에서