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

React context is undefined when the children are rendered using this.props.children

我在 React 中遇到了一个非常烦人的行为。我想使用 getChildContext 将上下文从父组件传递到子组件。只要我不在渲染函数中使用 {this.props.children} ,一切都会正常。如果我这样做,子组件的上下文是未定义的。

我附上了重现此行为的代码示例。我不明白为什么组件 Baz 的上下文 bar 字段是 undefined

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);

控制台输出:

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}

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

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

几个选项。

1) 在 Foo 上设置 child 上下文。
2) 在 Bar 中重新创建 <Baz> child。您可以使用 cloneWithProps 来做到这一点。

render: function() {
   console.log(this);
   return React.addons.cloneWithProps(this.props.children)
}

已更新 fiddle:https://jsfiddle.net/crob611/3h7pxnkx/2/

关于 React 项目讨论的问题:https://github.com/facebook/react/issues/3392