[英]Pass reference of a component to another one in ReactJS
在任何人急切地按下關閉按鈕之前,我已經看過以下問題: 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.
該文檔說,您可以附加事件來鏈接兩個沒有父子關系的組件。 但是我不知道如何。 有人可以給我一些指示嗎?
這將是Flux類型體系結構的理想用例。
您想要的是某人FooManager
能夠觸發兩個組件中的狀態更改。 或者,實際上,讓不同的組件通過Actions
觸發彼此的狀態更改。
Flux Todo-App教程完美地說明了您的用例!
之后,您將可以選擇使用Facebook的Flux實現或其他專精的實現。 我個人最喜歡的是Reflux
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.