关于前端:React的事件绑定为什么要bind-this

9次阅读

共计 744 个字符,预计需要花费 2 分钟才能阅读完成。

引入:绑定事件,咱们个别怎么写?

在 react 开发中绑定事件,咱们往往用这种形式:

此时咱们发现,this 指向了组件实例,合乎咱们的预期。

去掉 bind this 会如何?


能够看到,this 指向了 window

为什么会这样?

首先要晓得,JSX 语法实际上是 createElement 的语法糖

<div>Hello, {this.props.name}</div>
等价于
React.createElement(‘div’,null, `Hello,${this.props.name}` )

createElement 伪代码

function createElement(dom, params) {var domObj = document.createElement(dom);
  domObj.onclick = params.onclick;
  domObj.innerHTML = params.conent;
  return domObj
}

能够看到,咱们的自定义组件类中 onclick 绑定的事件,是作为 回调函数 绑定到 domObj.onclick 上的。

onclick 事件触发

当浏览器监听到 onclick 事件,则调用回调函数,此时的 this 就指向了 window

bind this 的原理

new 关键字

在应用 new 关键字时,构造函数(即 class)中的 this 都会强制赋值为新的对象。

应用 bind 将 this 的值绑定在函数中

箭头函数形式

为什么箭头函数形式不须要 bind this

  • 箭头函数内没有 this,默认用父级作用域的 this。
  • 当应用 new 关键字时,this 指向新对象,同时箭头函数中的 this 也被赋值为了新对象且永远不会更改指向。
  • 等价于如下模式
// 在构造函数内:let _this = this
funtion fn(){console.log(_this)
}

正文完
 0