Created
December 1, 2017 22:06
-
-
Save StevenJL/07d507325bf65195959d53b8f4ee4cb0 to your computer and use it in GitHub Desktop.
react_class_arrow
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
| // Without arrow functions | |
| class MyComponent extends React.Component { | |
| /* | |
| We define a method on MyComponent objects, that | |
| requires access to the MyComponent object as `this`. | |
| */ | |
| updateFoo() { | |
| this.setState({ | |
| foo: "bar" | |
| }) | |
| } | |
| render() { | |
| return ( | |
| <ChildComponent | |
| /* | |
| When we pass a function to a child component, we need | |
| to bind it to the `MyComponent` object since the function | |
| needs `this` to be set as the `MyComponent` object. | |
| */ | |
| callBack={ this.updateFoo.bind(this) } | |
| /> | |
| ) | |
| } | |
| } | |
| // With arrow functions | |
| class MyComponent extends React.Component { | |
| /* | |
| We define a property on MyComponent objects that points | |
| to an arrow function. The advantage with arrow functions is the | |
| `this` will refer to the MyComponent object, since it automatically | |
| sets `this` to the containing context of its definition. | |
| */ | |
| updateFoo = () => { | |
| this.setState({ | |
| foo: "bar" | |
| }) | |
| } | |
| render() { | |
| return ( | |
| <ChildComponent | |
| /* | |
| We don't need to bind because arrow functions set | |
| `this` as the context they were defined in, which | |
| is a `MyComponent` object. | |
| */ | |
| callBack={ this.updateFoo } | |
| /> | |
| ) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment