【问题标题】:Reason behind undefined 'this' in React Event Handler [duplicate]React事件处理程序中未定义的“this”背后的原因[重复]
【发布时间】:2019-11-05 06:40:02
【问题描述】:

我们都知道this 根据给定的 React 代码是未定义的。对于这个问题,我们有很多解决方案,比如绑定、箭头函数等。我想知道这种行为背后的原因。请解释this 引用的行为原因,而不是解决方案。

class Foo extends Component {

   clickHandler() {
      console.log(this);
   }

   render() {
      return <button onClick = {this.clickHandler}> Click Me </button>;
   }

}

【问题讨论】:

  • 其实我认为this一定是对创建按钮的引用。这就是它在纯 JavaScript 中的行为。但是在这里,在这段代码中,this 出乎意料地是未定义的。我想了解它的原因。
  • 接受者看这里freecodecamp.org/news/…
  • @MuhammadMuaaz 浏览这个medium.com/byte-sized-react/what-is-this-in-react-25c62c31480 你会得到更多的澄清
  • 谢谢你,@Harish。此链接对使用this 有很大帮助。也感谢@Vahid Akhtar。

标签: javascript reactjs this


【解决方案1】:

1)this.clickHandler=this.clickHandler.bind(this) 是返回一个新函数,其中对'this'的引用将引用该函数this是保存this当前值的方式,该值是作用域对构造函数的调用,以便以后可以调用该函数。 如果我们的函数不需要访问您组件的状态,那么请确保您不需要绑定 this。

2)箭头函数自动绑定this,这就是我们不需要使用.bind()方法的原因。

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 2015-06-26
    • 2017-10-25
    • 2015-11-28
    • 2016-04-17
    • 2017-03-19
    • 2016-07-20
    • 2015-06-17
    相关资源
    最近更新 更多