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


apologize in advance, new react.

in printdocument setting ohiddframe.onload = this.setprint; this.setprint getting error of cannot set property '__container__' of undefined this in setprint on first assignment.

i setting onclick={this.printdocument.bind(null, this.props.document.view_href)} on button in render(). how bind "this" actual event i'm assigning to?

much appreciate 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);   }, 

in es5 (classic) javascript :

onclick={this.printdocument.bind(this, this.props.document.view_href)} 

in es6 (with babel (https://babeljs.io/)) javascript :

onclick={() => this.printdocument(this.props.document.view_href)} 

es6 fat-arrows auto-bind this context function, , add more readability code.

more informations : http://exploringjs.com/es6/ch_arrow-functions.html


Comments