【问题标题】:What does bind(this) is exactly doing in this example of the React app? [duplicate]在这个 React 应用程序示例中,bind(this) 到底在做什么? [复制]
【发布时间】:2020-03-20 12:31:28
【问题描述】:

我不太确定.bind(this) 在这个例子中到底在做什么?是不是简单地将指定的函数连接到代码的其他组件如this.state

constructor(props) {
   super(props);
   this.state = {
      input: '',
      messages: []
   }
   this.handleChange = this.handleChange.bind(this);
   this.submitMessage = this.submitMessage.bind(this);
}

【问题讨论】:

标签: javascript reactjs bind


【解决方案1】:

“bind”方法用于在触发时将上下文(例如“this”)传递给javascript函数。

在这种情况下,react 组件的“this”传递给构造函数中的“handleChange”方法,
所以当“handleChange”将被调用时,如果在它的代码中使用了“this”, "this" 将获取父组件的值。

handleCahnge() {
  this.sendSomethingToServer(); // this is react component
}

否则,(不使用“绑定”)如果某些事件触发了上下文函数 将是事件的上下文(这将是事件目标元素而不是组件)

如果你使用箭头函数语法,你可以避免使用“绑定”语法:

handleCange = () => { this.sendSomethingToServer() };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2012-03-07
    • 2012-03-30
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多