1. 自動綁定 (事件綁定)
綁定this: React為什麼要這麼做?- 是js中this綁定方式決定的,和react工作方式無關。
- 函數處理, 是作為回調傳遞的,這樣就會丢失了上下文, 是以this為 undefined
- this不是預設指向在全局的嗎? 在嚴格模式下Strict mode, 就是個undefined, 不嚴格模式為全局
// 三種方式
// 1. 構造器綁定
constructor (props) {
super(props)
this.handleClick3 = this.handleClick3.bind(this)
}
// 2. 箭頭函數
<button onClick={() => this.handleClick2()}>
// 3. bind方式
<button onClick={this.handleClick4.bind(this)}>
2. 為什麼要綁定this?
LIN.JY666:[JS基礎] 7 - this, call/apply/bind/箭頭函數zhuanlan.zhihu.com
- 如果是個函數調用,那麼this指向函數内部,如果是非嚴格模式,那麼this指向window
- 如果是個對象裡的函數調用,那麼this指向該對象
- this要等到執行的時候,才确定是什麼。
為了綁定目前執行的環境, 目前執行的作用域
const object = {
name: '123',
fn: function () {
// 隐式綁定
console.log('this.name', this.name)
}
}
const name = 'test'
// 1. ?
object.fn() // 傳回'123' 對象裡的函數調用, this指向該對象
// 2. ?
objFn = object.fn
objFn() // 傳回 test 函數調用,那麼this指向函數内部,如果是非嚴格模式,那麼this指向window
// 3. 綁定, object.fn的this 使用object内部
objFnn = object.fn.bind(object)
objFnn() // '123'