在为事件分配方法时,在响应中访问`this`

编程入门 行业动态 更新时间:2024-10-28 19:27:25
本文介绍了在为事件分配方法时,在响应中访问`this`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

提前道歉,我对React很新。

Apologize in advance, I am very new to React.

在 printDocument 我设置 oHiddFrame.onload = this.setPrint; 甚至到 this.setPrint 但是收到错误不能在第一次分配时,在 setPrint 中为 设置未定义的属性'__container__'。

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 ( babeljs.io/ ))Javascript:

In ES6 (with babel (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.

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

更多推荐

在为事件分配方法时,在响应中访问`this`

本文发布于:2023-10-22 20:01:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1518560.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分配   事件   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!