[react]クラス構成部品this binding

12721 ワード

クラス構成部品this binding


クラス構成部品を復習する際、constructor内部でクラス内部宣言の方法をバインドする理由が明確に理解されていないため、再確認します.
まず、ボタンをクリックするたびにisToggleOnの値が変わり、ボタンのテキストを変更するコードが作成されます.
import React from 'react';
import './app.css';

class App extends React.Component {
	constructor(props) {
    	super(props);
        this.state = {isToggleOn: true};
        
        this.handleClick = this.handleClick.bind(this);
    }
    
    handleClick() {
      console.log('handleClick func: ',this);
    	this.setState(state => ({
        	isToggleOn: !state.isToggleOn
      }));
    }
    
    render() {
    	return (
        	<button onClick={this.handleClick}>
            	{this.state.isToggleOn ? 'ON' : 'OFF'}
          </button>
      );
    }
}

コンストラクション関数にバインドします。

constructor(props) {
  super(props);
  this.state = {isToggleOn: true};

  this.handleClick = this.handleClick.bind(this);
}
この場合、ボタンをクリックすると、私たちが試みたように、thisはAppcomponentを指し、よく動作します.

コンストラクション関数にバインドされていません

constructor(props) {
  super(props);
  this.state = {isToggleOn: true};
}
しかしbindingがなければhandleClick func内部のthisはundefinedを指し,うまく機能しない.

理由:


thisを学習する場合、呼び出す方法によってthis値が異なりますが、この場合、ボタンをクリックすると함수방식으로 호출하기 때문에 전역 객체인 window를 가리켜야 하지만 strict mode가 적용되어 있어 undefined값이 나오게 된 것になります.
だから이를 해결하려면 bind() 메서드를 사용하여 명시적으로 바인딩을 해주거나 arrow function방식으로 변경は私たちが望んでいるこの値を得ることができます.
constructor(props) {
  super(props);
  this.state = {isToggleOn: true};

  // this.handleClick = this.handleClick.bind(this);
}

handleClick = () => {
  console.log('handleClick func: ',this);
  this.setState(state => ({
    isToggleOn: !state.isToggleOn
  }));
}
または
    handleClick() {
      console.log('handleClick func: ',this);
    	this.setState(state => ({
        	isToggleOn: !state.isToggleOn
      }));
    }
    
    render() {
      console.log(this);
    	return (
        	<button onClick={() => this.handleClick()}>
            	{this.state.isToggleOn ? 'ON' : 'OFF'}
          </button>
      );
    }

Reference

  • https://velog.io/@jiseong/JS-this