Created
March 22, 2015 06:57
-
-
Save mikechau/c6ea0496c2343a37ba29 to your computer and use it in GitHub Desktop.
react bind
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://groups.google.com/forum/#!topic/reactjs/Xv9_kVoJJOw | |
I found this confusing as well and actually found this thread after a search for something like 'react bind null' or something. So I'll briefly explain my surface-level understanding for future searchers. | |
It turns out that react automatically binds methods to 'this' on component mount. This is helpful because it allows you to directly pass functions (e.g. this.handleChange) to a child component without worrying about the value of 'this' when the function is actually called. React then the replaces the standard Function.prototype.bind method with its own function to help stop you from doing anything silly (like trying to change the already-bound value of 'this'), so you instead have to pass 'null' to say "I understand this will only alter the arguments". | |
However, react (for whatever reason) does not do this for function calls within the same component (i.e. this.myFunction()). Possibly because it's a little pointless - 'this' will be the correct value most of the time. Unfortunately, this means you can't pass 'null' to the value of bind (as above) when you want to partially apply functions, because that will *actually* set the value of 'this' to be null inside the function. | |
In real terms, this means if you want to set the first argument by calling .bind on a function... | |
- ...passed in via props, pass null as the first argument e.g. this.props.onChange.bind(null, "first arg") | |
- ...taken from 'this', pass 'this' as the first argument e.g. this.handleChange.bind(this, "first arg") | |
The place where I think this information should go (http://facebook.github.io/react/tips/communicate-between-components.html) doesn't mention it and other places (http://stackoverflow.com/a/21560475/2352259, the jsfiddle from http://stackoverflow.com/a/20796299/2352259) have tantalisingly nice examples and to-the-point answers, but no elaboration. | |
Maybe I just didn't read the documentation properly... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/