小编典典

将方法分配给事件时,在react中访问`this`

reactjs

预先道歉,我对React非常陌生。

printDocument我设置oHiddFrame.onload = this.setPrint;
甚至this.setPrint,但我得到的误差Cannot set property '__container__' of undefinedthissetPrint第一个任务。

onClick={this.printDocument.bind(null, this.props.document.view_href)}在render()中设置按钮。如何将“ 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);
  },

阅读 243

收藏
2020-07-22

共1个答案

小编典典

ES5经典 )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

2020-07-22