日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

react:理解“為了在回調中使用 `this`,這個綁定是必不可少的”

作者:你吃香蕉嗎? 更新時間: 2023-04-20 編程語言

一、官網代碼

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // 為了在回調中使用 `this`,這個綁定是必不可少的
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

二、官網解釋

你必須謹慎對待 JSX 回調函數中的?this,在 JavaScript 中,class 的方法默認不會綁定?this。如果你忘記綁定?this.handleClick?并把它傳入了?onClick,當你調用這個函數的時候?this?的值為?undefined

這并不是 React 特有的行為;這其實與?JavaScript 函數工作原理有關。通常情況下,如果你沒有在方法后面添加?(),例如?onClick={this.handleClick},你應該為這個方法綁定?this

三、ES6 class

class Example {
    constructor(a, b) {
        this.a = a;
        this.b = b;
        console.log('Example');
    }
    sum() {
        return this.a + this.b;
    }
}
let exam1 = new Example(2, 1);
let exam2 = new Example(3, 1);
console.log(exam1.sum()); // 3
console.log(exam2.sum()); // 4

以上代碼可以看出es6中的class是不需要給方法單獨綁定this的

四、ES6 class不需要單獨綁定this,那為什么react中要單獨綁定this?

關鍵的一句話:當函數作為回調函數被調用時

onClick={this.handleClick} 就是將handleClick作為回調函數使用的

改造一下第三點的代碼,將exam1.sum和exam2.sum作為回調函數使用:

class Example {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
    sum() {
        return this.a + this.b;
    }
}
let exam1 = new Example(2, 1);
let exam2 = new Example(3, 1);
function getSum(cb) {
    console.log('cb', cb());
}
getSum(exam1.sum)
getSum(exam2.sum)

此時代碼執行報錯:

Uncaught TypeError: Cannot read properties of undefined (reading 'a')

顯然 this 此時是undefined

五、作為回調函數時正確的代碼

class Example {
    constructor(a, b) {
        this.a = a;
        this.b = b;
        this.sum = this.sum.bind(this);
    }
    sum() {
        return this.a + this.b;
    }
}
let exam1 = new Example(2, 1);
let exam2 = new Example(3, 1);

function getSum(cb) {
    console.log('cb', cb());
}
getSum(exam1.sum)
getSum(exam2.sum)

原文鏈接:https://blog.csdn.net/m0_47135993/article/details/126174562

欄目分類
最近更新