【发布时间】:2015-03-12 18:01:46
【问题描述】:
如何使用 Reactjs 保留对动态子引用的引用。我有一个管理孩子的主组件。该组件需要访问其子组件的状态,以确定每个子组件是否已完成他们负责的流程。除非所有子组件都完整,否则不能说主组件是完整的。
我已经尝试过文档中提到的关于 refs 回调的内容。这种方法的问题是,一旦所述组件安装,React 不会在 Ref Callback Attribute 部分中通过 http://facebook.github.io/react/docs/more-about-refs.html 中提到的组件引用。
请参阅下面的示例脚本,其中详细说明了我的问题。
var App = React.createClass({
registerComponent: function (comp){
//logic to retain a reference to the component
//The problem with this approach is that React does not pass the component reference as mentiond
//here http://facebook.github.io/react/docs/more-about-refs.html in the he ref Callback Attribute //section.
},
isComplete: function(){
//check all child components to see if the App is complete
for (comp in this.refs){
//if any component is not complete then the App as a whole is not complete
if(!comp.state.complete){
return false;
}
}
return true;
},
render: function() {
return(
<div className="Container">
{this.state.arrayOfdata.map(function(value){
if(value === class1Value){
return <class1 ref={this.registerComponent}/>;
}
else if (value === class2Value){
return <Class2 ref={this.registerComponent} />
}
else if (value === class3Value){
return <Class3 ref={this.registerComponent}/>
}
}.bind(this))}
</div>
);
}
});
var class1 = React.createClass({
getInitialState:function(){
return {
complete: false;
}
},
render: function (){
return(
<span className="class1"/>
)
}
});
var class2 = React.createClass({
getInitialState:function(){
return {
complete: false;
}
},
render: function(){
return(
<span className="class2"/>
);
}
});
var class3 = React.createClass({
getInitialState:function(){
return {
complete: false;
}
},
render: function(){
return(
<span className="class3"/>
);
}
});
var AppHandle = React.render(<App/>,
document.getElementById('content')
);
我可能做错了什么?他们是实现我尝试使用 this.refs 数组的更好方法吗?
【问题讨论】:
-
什么类型的事件会触发状态从不完整到完成的变化?
-
@Mark 由孩子管理的触摸事件。触摸后,孩子的状态会从不完整变为完整。我想确保所有子组件在进入应用程序周期的下一个阶段之前都已收到用户的交互。
-
arrayOfdata 中的 class(x)Values 是否唯一?从 map 函数中的
if(value === class1Value)来看,这些对象似乎是相同的。
标签: javascript facebook reactjs