为什么我们不需要在React中绑定箭头功能? [英] Why we don't need to bind the arrow function in React?

查看:90
本文介绍了为什么我们不需要在React中绑定箭头功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道我们需要在React中绑定函数以使其起作用.我确实知道我们为什么需要绑定它.

We all know that we need to bind function in React to make it work. I do know why do we need to bind it.

但是我不确定为什么我们不需要绑定箭头功能.

But I'm not sure why we don't need to bind arrow function.

示例: 使用箭头功能(无需绑定)

Example: Using arrow function (No bind in required)

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

};

现在,使用功能(需要绑定)

Now, Using function (Bind is required)

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

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

};

我不是在问为什么我们需要绑定函数.我只想知道为什么箭头功能不需要绑定.

I'm not asking why we need bind in function. I just want to know why binding is not required in arrow function.

谢谢.

推荐答案

仅因为arrow函数的上下文中没有以下内容:

Simply because arrow function does not have the following in its context:

  • 这个
  • 参数
  • 超级
  • new.target

因此,当您在箭头函数中引用此变量时,会将 this 视为任何其他变量,并首先在其范围内查找其声明,并且找不到它,因此它将搜索上限范围 this 指所需的react组件类,因此我们无需将 this 绑定到该类.

So when you reference this inside an arrow function it treat this as any other variable and look for its declaration in its scope first and it can not find it so it search the upper scope which is the this referring to the react component class which what is required so we do not need to bind the this to the class.

这篇关于为什么我们不需要在React中绑定箭头功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆