2015-04-08 43 views
2

在任何人急切按下关闭按钮之前,我已经看过以下问题:ReactJS Two components communicating。我的问题恰恰是目前公认的答案中出现的第三种情况。将组件的引用传递给ReactJS中的另一个组件

我正在使用ReactJS构建两个组件。出于HTML原因(和演示文稿),我希望我的两个组件位于页面的两个不同位置。

就目前而言,我有以下的模式,对应场景#2:

FooForm = React.createClass({ 
    ... 
}); 

FooList = React.createClass({ 
    ... 
}); 

FooManager = React.createClass({ 
    ... 

    render: function() { 
     return (
      <div> 
       <FooForm ref="form" manager={this} /> 
       <FooList ref="list" /> 
      </div> 
     ); 
    } 
}); 

React.render(
    <FooManager someProp={value} />, 
    document.getElementById('foo') 
); 

这给了像:

<div id="foo"> 
    <form>Form generated with the render of FooForm</form> 
    <ul>List generated with the render of FooList</ul> 
</div> 

不过,我想有这样的事情:

<div id="fooform"> 
    <form>Form generated with the render of FooForm</form> 
</div> 
<!-- Some HTML + other controls. Whatever I want in fact --> 
<div>...</div> 
<div id="foolist"> 
    <ul>List generated with the render of FooList</ul> 
</div> 

这里的问题是:如何保持参考每个组件?或者至少链接表单 - >列表?

我试图创建前FooList并通过参照当前的经理,但我得到以下警告/错误:

Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref. 

的文档说,你可以将事件附加到两个组件里面做链接没有亲子关系。但我不知道如何。有人能给我一些指点吗?

回答

3

Less Simple Communication教训从react-training具有的你怎么能&状态横向移动动作,以避免产生相关组件之间的明确联系一个很好的例子。

你不需要跳过一个完整的Flux实现来获得这种方法的好处,但它是一个很好的例子,可以引导你到达Flux,最终是否需要它或类似的东西。

请注意,这要求您基于状态更改来建模组件之间的关系,而不是显式地将引用传递到组件实例(如上所述)或绑定到管理状态的组件的回调。

+1

正是我需要的。我已经在15分钟内实现了这个架构,在我的代码库中几乎没有什么变化,它的作用就像一个魅力:)非常感谢。 –

2

这将是Flux型架构的完美用例。

你想要的是某人FooManager能够触发两个组件的状态变化。或者,事实上,让不同的组件通过Actions触发对方的状态更改。

Flux Todo-App Tutorial完美地展示了您的使用案例!

之后,你会有使用Facebook的Flux或其他gazillion实施的选择。 我个人最喜欢的是Reflux

+0

看起来像我真正需要的......我会在接下来的几个小时内尝试。谢谢:) –

相关问题