ReactJS - Assign Context / Owner in 13.x

I am trying to create a child that has already been initialized and passed through a prop. My child depends on its context, but I don't know how to apply this context before rendering. Example:

http://jsfiddle.net/5qyqceaj/1/ (code below on React 0.13.3):

var Parent = React.createClass({
    childContextTypes: {
        test: React.PropTypes.string
    },
    getChildContext: function() {
        return { test: "Working :)" };
    },
    render: function() {
        return (
            <div>
                <b>Initialized Globally:</b><br/> {this.props.child}
                <hr/>
                <b>Initialized Inline:</b><br/> <Child/>
            </div>
        );
    }
});

var Child = React.createClass({
    contextTypes: {
        test: React.PropTypes.string
    },
    render: function() {
        return <div><h1>Context: {this.context.test || "Broken"}</h1></div>;
    }
});

var ChildInstance = <Child/>;

React.render(<Parent child={ChildInstance} />, document.getElementById('container'));

      

The above example <Child/>

does not globally inherit the context passed by Parent when initialized.

According to https://github.com/facebook/react/issues/3451#issuecomment-104978224 this is an open issue with React 0.13.x where the context is currently assigned by the owner and at 0.14 they will inherit it from the parent.

There are three ways I can imagine solving this:

  • Find a way to assign context to a component when rendered, or manually switch the owner of an item.
  • Restore items by passing in props and tags
  • Wait 0.14

2 is really not supported for more complex structures and 3 is surrender, are there any ways to achieve 1?

+3


source to share


1 answer


You can use React.cloneElement

to re-assign the owner of a React element. It will return a new item. Please note that you will need to pass the new propertyref

, otherwise the previous owner will be retained.



In your case, you will be cloning this.props.child

in the render method Parent

.

+1


source







All Articles