React : method 내부 this 사용하는 여러가지 방법
방법 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이 코드도 가장 적게 들어가고 편리함!
Author And Source
이 문제에 관하여(React : method 내부 this 사용하는 여러가지 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@whdms3368/React-기본기-익히기-method-내부-this-사용하는-여러가지-방법저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)