Context in Facebook's React JS framework
Asked Answered
H

2

6

I'm struggling to understand how context works in Facebook's React JS framework.

When passing a specification to React.createClass, certain methods (notably event handlers) seem to require the use of React.autoBind to 'bind callbacks to the component'. Other methods (notably render()) don't have this requirement but still happily reference this.props or this.state.

What is the context of 'this' as used by the render() method, if it's not the component ?

Hallowmas answered 25/6, 2013 at 10:18 Comment(0)
F
4

That's because they kind of already does autoBind for internal methods such as render. In fact, if you call autoBind and pass those methods you'll get an error.

For custom methods, initially the idea is that you might want to stick to whatever context you want to assign, but this is changed in 0.4.x (http://facebook.github.io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html).

Basically because the bound this is most of the time what you want, from now on every method in createClass will now autoBind by default.

Frohne answered 7/7, 2013 at 3:31 Comment(0)
V
0

In any component framework (not just react), event handlers need manual management of the this reference because they're registered into the DOM as a callback function, not method. In react 0.3 you could bind the this reference yourself, or you can use React.autoBind which is more efficient. In React 0.4, all event handlers get bound by the framework on their way into the DOM, so you don't have to think about it anymore.

thus the this reference is always a reference to a react component instance.

Vargueno answered 4/8, 2013 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.