将方法分配给事件时访问“this”以做出反应

Accessing `this` in react when assigning method to an event

提前致歉,我是 React 的新手。

printDocument 中,我将 oHiddFrame.onload = this.setPrint; 甚至设置为 this.setPrint,但在 setPrint 中收到 thisCannot set property '__container__' of undefined 错误在第一个任务上。

我在 render() 中的按钮上设置 onClick={this.printDocument.bind(null, this.props.document.view_href)}。如何将 "this" 绑定到我分配给它的实际事件?

非常感谢任何帮助或建议。

  closePrint: function () {
    document.body.removeChild(this.oHiddFrame.__container__);
  },

  setPrint: function () {
    this.contentWindow.__container__ = this;
    this.contentWindow.onbeforeunload = this.closePrint;
    this.contentWindow.onafterprint = this.closePrint;
    this.contentWindow.focus();
    this.contentWindow.print();
  },

  printDocument: function (url) {
    var oHiddFrame = document.createElement("iframe");
    oHiddFrame.onload = this.setPrint;
    oHiddFrame.style.visibility = "hidden";
    oHiddFrame.style.position = "fixed";
    oHiddFrame.style.right = "0";
    oHiddFrame.style.bottom = "0";
    oHiddFrame.src = url;
    document.body.appendChild(oHiddFrame);
  },

您的 onClick 需要如下所示:onClick={this.printDocument.bind(this)},否则它不会正确绑定到按钮。

printDocument() 方法中,您可以随时调用 this.props 并在其中使用您需要的任何内容。之后您还可以在方法内部直接操作事件。

不确定你问的是不是这个。

this 作为第一个参数传递给 bind。第一个参数是上下文,this 应该在绑定函数中,但您当前传递的是 null.

onClick={this.printDocument.bind(this, this.props.document.view_href)}

事件对象,一个 SyntheticMouseEvent 实例,将是处理程序的最后一个参数。您可以向函数声明添加另一个参数并引用它:

 printDocument: function (url, event) {
   ...
 }

ES5 (经典) Javascript :

onClick={this.printDocument.bind(this, this.props.document.view_href)}

ES6中(使用babelhttps://babeljs.io/))Javascript :

onClick={() => this.printDocument(this.props.document.view_href)}

ES6 fat-arrows 自动绑定 this 上下文到函数,并增加代码的可读性。

更多信息: http://exploringjs.com/es6/ch_arrow-functions.html