在这个 React 应用程序示例中,bind(this) 究竟在做什么?

What does bind(this) is exactly doing in this example of the React app?

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

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

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

在这种情况下 "this" 的反应组件传递给构造函数中的 "handleChange" 方法,
所以当 "handleChange" 将调用时,如果其中使用了 "this" 代码, "this" 会得到父组件的值

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

否则,(不使用"bind")如果某个事件触发了函数上下文 将是事件的上下文(这将是事件目标元素而不是组件)

您可以避免使用 "bind" 语法,因为您使用箭头函数语法:

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