为了更好地理解我的问题,请查看我的组件图:https://app.box.com/s/rkq9bhyzs00971x6xgpq8exmvu4zzjlt
通过查看图像,您可以看到我基本上有一个组件结构
Browse Widget
-Main Menu
-Display
-SubMenu
-SubCategory
-SearchBar
-Video Display
我的显示组件包含从 API 提取的所有组件。但它们依赖于了解 MainMenu 组件处于事件状态的选项卡才能进行正确的查询。每次单击选项卡时,我都想更新 Display 的状态(使用来自 API 的新调用)。这可能吗?
我对如何更改不是直接处理事件本身的组件的状态感到有点困惑?
我是否需要更改我的组件结构,或者是否有更好的方法来做到这一点?您可以指出/制作任何示例吗?
最佳答案
我建议跟踪事件选项卡并管理来自 DisplayController 组件的所有 API 调用。使用下面的结构应该足以帮助您入门。数据获取函数位于 Display 组件中,并通过 props 中的回调传递给其他组件。
var DisplayController = React.createClass({
getInitialState: function(){
return {
active_tab: 0, display_data: [],
tabs: [{name: 'Tab 0', tab_id: 0}, {name: 'Tab 1', tab_id: 1}, {name: 'Tab 2', tab_id: 2}]
};
}
changeTab: function(tab_id){
this.setState({active_tab: tab_id}, apiCall);
}
apiCall: function(){
//make api call based off of this.state.active_tab
//this.setState({display_data: whatever you get back from api})
}
render: function(){
dprops = {
tabs: this.state.tabs.
changeTab: this.changeTab,
active_tab: this.state.active_tab,
display_data: this.state.display_data
};
return (<MainMenu {...dprops}/>);
}
});
var MainMenu = React.createClass({
changeTab: function(tab_id){
this.props.changeTab(tab_id);
},
render: function(){
tabs = this.props.tabs.map(function(tab){
return <Tab onClick={this.changeTab.bind(tab.tab_id)} name={tab.name} key={tab.tab_id}/>
}.bind(this));
return(
<div>
{tabs}
<Display {...this.props} />
</div>
);
}
});
var Tab = React.createClass({
render: function(){
// make your tab component here from this.props.name
}
});
var Display = React.createClass({
render: function(){
// make your display component here using data from this.props
}
});
关于javascript - 更改 ReactJs 中不直接处理事件的组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30959471/