在任何人急切按下关闭按钮之前,我已经看过以下问题: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.
的文档说,你可以将事件附加到两个组件里面做链接没有亲子关系。但我不知道如何。有人能给我一些指点吗?
正是我需要的。我已经在15分钟内实现了这个架构,在我的代码库中几乎没有什么变化,它的作用就像一个魅力:)非常感谢。 –