Question

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 ?

Était-ce utile?

La solution

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.

Autres conseils

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.

Nowday context in ReactJs is a new hook of ReactJs (since v16.6.3). It is designed to pass properties down through the component tree without hard coding these properties for each nested element in the parent elements. The basic example:

    // Design context
    const DesignContext = React.createContext({background: 'light'});

    // User context
    const UserContext = React.createContext({
        name: 'NewUser',
    });


    // A component may consume multiple contexts
    function Content() {
        return (
            <DesignContext.Consumer>
                {background => (
                    <UserContext.Consumer>
                        {user => (
                            <ProfilePage user={user} background={background} />
                        )}
                    </UserContext.Consumer>
                )}
            </DesignContext.Consumer>
        );
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top