React : method 내부 this 사용하는 여러가지 방법

🍒Jooooooo_eun🍒·2021년 12월 8일
0

React basic

목록 보기
5/16
post-thumbnail

방법 1. 이벤트 핸들러 바로옆에 bind 붙이기

class Component extends React.Component {
      state = {
        count : 0,
      }
      render() {
        return ( 
          <div>
            <p>{this.state.count}</p>
            <button onClick={this.click.bind(this)}> //this 사용 선언
                클릭
            </button>
          </div>
        )
      }
      click() {
        this.setState((state) => ({...state,count:state.count+1}));
      }
    }

방법2. constructor(props) 활용해 해당 method에 bind(this) 붙이기

  class Component extends React.Component {
      state = {
        count : 0,
      }
      constructor(props) {
        super(props);
        this.click = this.click.bind(this); // this 사용 선언
      }
      render() {
        return ( 
          <div>
            <p>{this.state.count}</p>
            <button onClick={this.click}>
                클릭
            </button>
          </div>
        )
      }
      click() {
        this.setState((state) => ({...state,count:state.count+1}));
      }
    }

방법3.method 를 함수형으로 바꿔주기 (추천)

class Component extends React.Component {
      state = {
        count : 0,
      }
      render() {
        return ( 
          <div>
            <p>{this.state.count}</p>
            <button onClick={this.click}>
                클릭
            </button>
          </div>
        )
      }
      click =() => { // this 사용가능
        this.setState((state) => ({...state,count:state.count+1}));
      }
    }

개인적으로 방법 3이 코드도 가장 적게 들어가고 편리함!

profile
먹은만큼 성장하고 싶은 초보 개발자의 끄적끄적 개발메모장 ✍

0개의 댓글