在有人急切地按下关闭按钮之前,我已经看过以下问题:ReactJS Two components communicating 。我的问题正是当前接受的答案中开发的第三种情况。
我正在使用 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.
文档说您可以附加事件来链接两个没有父子关系的组件。但我不明白怎么办。有人可以给我一些指示吗?
最佳答案
Less Simple Communication教训来自react-training有一个很好的示例,说明如何横向移动操作和状态,以避免在相关组件之间创建显式链接。
您不需要跳入完整的 Flux 实现来获得这种方法的好处,但如果您最终需要它或类似的东西,它是一个很好的示例,可以引导您使用 Flux。
请注意,这要求您根据不断变化的状态对组件之间的关系进行建模,而不是显式传递对组件实例的引用(如上面所做的那样)或绑定(bind)到管理状态的组件的回调。
关于javascript - 在 ReactJS 中将一个组件的引用传递给另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29510301/