【问题标题】:What bind(this) is actually doing in ReactJS?在 ReactJS 中 bind(this) 实际上在做什么?
【发布时间】:2018-08-24 06:54:26
【问题描述】:
this.something = this.something.bind(this)

上面这行实际上在做什么?我是新手,所以请以技术方式给出一个基本级别的解释(以我的理解)

【问题讨论】:

  • 你不必使用绑定,例如:onClick={this.doSomething},如果定义为 onClick={() => this.doSomething()} 没有它也可以工作
  • @thsorens 我得到了你的,你能从技术上解释一下吗

标签: reactjs react-state-management


【解决方案1】:

上面那行实际上在做什么?

Use of the JavaScript 'bind' method

bind 创建一个新函数,将其设置为传递给bind() 的第一个参数。

这是必要的,因为在 DOM 库和 JavaScript 的许多部分中,隐藏/隐式 this 函数参数已更改为指向不同的幕后对象。

一个很好的例子涉及 JavaScript 中的事件处理程序,其中 this 参数并非看起来那样:

HTML:

<button id="someButton" name="Bar">Hello</button>

JavaScript(在 DOM 加载后运行):

function Foo() {
    this.name = "Foo";
}
Foo.prototype.eventHandler( event ) {
    console.log( event.type ); // will always print "click"
    console.log( this.name ); // will print either "Foo" or "Bar"
}

var button = document.getElementById("someButton"); // HTMLButton

var fooInstance = new Foo(); // fooInstance.name == "Foo"

button.addEventListener( 'click', fooInstance.eventHandler );

如果您运行此代码并单击按钮并在 Foo.prototype.eventHandler 中设置断点,那么您将看到 this.name"Bar" 而不是 "Foo" - 即使您传入了对 fooInstance.eventHandler 的引用调用时哪个肯定知道fooInstance

没有。

这是因为 DOM API 将 fooInstance.eventHandlerthis 更改为 button 实例。我不知道确切的原因,但我相信这与保持与老式基于 HTML 属性的 JavaScript 事件处理程序的向后兼容性有关:

<button onclick="alert(this.name)" name="Baz">Click me</button>

(其中this指的是包含HTMLElement

所以使用.bind 覆盖库对this 的更改。您可能会认为.bind(this) 返回另一个Functionthis 参数无论如何都会更改,但实际上并没有。这是因为返回的Function 实际上根本无法更改其this 成员,这与大多数Function 对象不同。

在 ReactJS 中:

foo = foo.bind(this) 的使用并不是 ReactJS 独有的(它是 JavaScript 的一部分),但它是 ReactJS 中的一个习惯用法:

why do you need to bind a function in a constructor

这是因为 React 不想弄乱 ES6 规范(将 this 绑定到其类中的函数不在 ES6 类规范中),但同时又想给它的用户提供 ES6 类语法的便利.您可以在下面阅读更多相关信息。

【讨论】:

    猜你喜欢
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2020-12-05
    • 2011-01-17
    • 2018-10-13
    • 2017-04-28
    相关资源
    最近更新 更多