提前道歉,我对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);
},
在ES5(classic)中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) {
...
}