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

一世执手 提交于 2019-12-01 12:08:44

问题


Apologize in advance, I am very new to React.

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.

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

回答1:


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 to the function, and add more readability to code.

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




回答2:


Your onClick needs to look like this: onClick={this.printDocument.bind(this)}, otherwise it won't bind to the button correctly.

Inside printDocument() method, you can always call this.props and use whatever you need in there. You can also manipulate the event right inside the method afterward.

Not sure if that's what you are asking.




回答3:


Pass this as the first argument to bind. The first argument is the context, what this should be inside the bound function, but you're currently passing null.

onClick={this.printDocument.bind(this, this.props.document.view_href)}

The event object, a SyntheticMouseEvent instance, will be the last argument to your handler. You can add another argument to the function declaration and reference it:

 printDocument: function (url, event) {
   ...
 }


来源:https://stackoverflow.com/questions/38513432/accessing-this-in-react-when-assigning-method-to-an-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!