使用this.props.children呈现子项时,React上下文未定义

Giu*_*Pes 12 javascript reactjs react-jsx

我在React面临一个非常讨厌的行为.我想使用上传从父组件到子组件的上下文getChildContext.只要我不在{this.props.children}渲染功能中使用,一切正常.如果我这样做,则子组件的上下文未定义.

我附加了一个重现此行为的代码示例.我无法弄清楚为什么bar组件的上下文字段Bazundefined.

var Baz = React.createClass({
 contextTypes: {
   bar: React.PropTypes.any
 },
 render: function() {
   console.log(this.context);
   return <div />;
 }
});

var Bar = React.createClass({
 childContextTypes: {
   bar: React.PropTypes.any
 },

 getChildContext: function() {
   return {
     bar: "BAR"
   };
 },

 render: function() {
   return (<div>{this.props.children}</div>);
 }
});

var Foo = React.createClass({
 render: function() {
   return <Bar>
      <Baz />
   </Bar>;
 }
});

console.log(React.version);

React.render(<Foo />, document.body);
Run Code Online (Sandbox Code Playgroud)

控制台输出:

Warning: owner-based and parent-based contexts differ (values: `undefined` vs `BAR`) for key (bar) while mounting Baz (see: http://fb.me/react-context-by-parent)
Inline JSX script:10 Object {bar: undefined}
Run Code Online (Sandbox Code Playgroud)

JSFiddle:https://jsfiddle.net/3h7pxnkx/1/

Cro*_*rob 12

因此,似乎所有组件都获得了创建它们的子环境.在这种情况下,它<Baz />是作为其一部分创建的Foo,因此它从中获取子上下文Foo,这就是它未定义的原因.

几个选项.

1)设置子上下文Foo.
2)重新创建<Baz>孩子Bar.您可以使用cloneWithProps执行此操作.

render: function() {
   console.log(this);
   return React.addons.cloneWithProps(this.props.children)
}
Run Code Online (Sandbox Code Playgroud)

更新的小提琴:https://jsfiddle.net/crob611/3h7pxnkx/2/

讨论它的反应项目问题:https://github.com/facebook/react/issues/3392

  • 值得注意的是,正如警告所示,计划是这种行为将在React v0.14中发生变化,因此`Baz`将从其父"Bar"而不是其所有者"Foo"获取其上下文. (3认同)