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

做~自己de王妃 提交于 2019-12-01 13:47:35

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

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.

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