【问题标题】:Why I have to bind this to methods in class component in Reactjs为什么我必须将它绑定到 Reactjs 的类组件中的方法
【发布时间】:2021-12-02 14:12:59
【问题描述】:

我已经搜索并阅读了这个问题很长时间,但仍然无法理解。 所以在一个 React 类组件中,你会写这样的方法:

class Test extends React.Component {
  constructor(props){
   super(props)
   this.method = this.method.bind(this)
  }

  method() {
    ...
  }
}

如果“this”默认没有绑定,为什么我们可以使用“this.method”呢? “this”在“this.method”和“bind.(this)”中是什么意思。它们是一样的吗?

这条线:this.method = this.method.bind(this) 真的让我很困惑。请帮我解释这一行中的 3 个“this”中的每一个。谢谢。

【问题讨论】:

    标签: javascript reactjs class binding this


    【解决方案1】:

    当您pass it to a child component 时,将方法绑定到“this”很有用。当你这样做的时候,通常是为了在子组件执行这个方法时能够改变父组件的本地状态。有点像说

    "我想让这个方法绑定到这个类,也就是说,如果它被调用 在任何地方,此方法中对“this”的引用均指 THIS 类”



    这是一篇有趣的文章,详细解释了这一点:
    https://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

    【讨论】:

    猜你喜欢
    • 2017-02-24
    • 2022-06-15
    • 1970-01-01
    • 2020-04-06
    • 2013-10-03
    • 2016-12-02
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多