当将方法分配给事件时,访问中的“this”会做出反应

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

本文关键字:this 分配 方法 事件 访问      更新时间:2023-09-26

提前道歉,我对React很陌生。

printDocument中,我甚至将oHiddFrame.onload = this.setPrint;设置为this.setPrint,但在第一次分配时,setPrint中的this出现Cannot 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);
  },

ES5classic)中Javascript:

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

ES6中(带有babel(https://babeljs.io/))Javascript:

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

ES6胖箭头自动将这个上下文绑定到函数,并为代码增加更多可读性。

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

您的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) {
   ...
 }