react-autobind-component
Use this alternative to React.Component
to automatically bind your methods.
TL;DR
When using react-autobind-component
instead of React.Component
, the onClick()
method gets automatically bound, so this.foo
will be bar
:
;; // <-- foo = 'bar'; { thisfoo; // -> 'bar' } { return <button onClick=thisonClick> Click here </button> ; }
Use case
Problem:
; foo = 'bar'; { thisfoo; // -> undefined, because `this` refers to the caller of onClick } { return <button onClick=thisonClick> Click here </button> ; }
How you are used to solve this:
; foo = 'bar'; { superprops; thisonClick = thisonClick; // <- old solution } { thisfoo; // -> 'bar' } { return <button onClick=thisonClick> Click here </button> ; }
How you are going to solve this from now on:
;; // <- new solution foo = 'bar'; { thisfoo; // -> 'bar' } { return <button onClick=thisonClick> Click here </button> ; }
How does it work?
Very simple:
;; { super; ; };
The real version is slightly smarter, since it skips binding for methods like constructor
, componentWillMount
, render
, etc.