问题描述
提前道歉,我对React很新。
Apologize in advance, I am very new to React.
在 printDocument
我设置 oHiddFrame.onload = this.setPrint;
甚至到 this.setPrint
但是收到错误不能在第一次分配时,在
的属性'__container__'。 setPrint
中为
设置未定义
In printDocument
I am setting the oHiddFrame.onload = this.setPrint;
even to this.setPrint
but am getting an error of Cannot set property '__container__' of undefined
for this
in setPrint
on the first assignment.
我正在设置 onClick = {this.printDocument.bind(null,this.props.document.view_href)}
在渲染()按钮上。如何将this绑定到我分配给它的实际事件?
I am setting onClick={this.printDocument.bind(null, this.props.document.view_href)}
on button in render(). How do I bind "this" to the actual event I'm assigning it to?
非常感谢任何帮助或建议。
Much appreciate any help or advise.
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);
},
推荐答案
在 ES5 (经典)Javascript:
In ES5 (classic) Javascript :
onClick={this.printDocument.bind(this, this.props.document.view_href)}
在 ES6 (与 babel ())Javascript:
In ES6 (with babel (https://babeljs.io/)) Javascript :
onClick={() => this.printDocument(this.props.document.view_href)}
ES6 fat-arrows auto-bind 此函数的上下文,并为代码添加更多可读性。
ES6 fat-arrows auto-bind this context to the function, and add more readability to code.
更多信息:
这篇关于在为事件分配方法时,在响应中访问`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!