使用this.props.children

时间:2015-05-19 17:11:40

标签: javascript reactjs react-jsx

我在React面临一个非常讨厌的行为。我想使用getChildContext将上下文从父组件传递给子组件。只要我在渲染函数中不使用{this.props.children},一切都可以正常工作。如果我这样做,则子组件的上下文未定义。

我附加了一个重现此行为的代码示例。我无法弄清楚为什么组件bar的上下文的Baz字段为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/

1 个答案:

答案 0 :(得分:12)

所以看起来所有组件都获得了创建它们的子环境。在这种情况下,<Baz />被创建为Foo的一部分,因此它从Foo获取子上下文,这就是它未定义的原因。

几种选择。

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

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

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

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