簡體   English   中英

更改不直接在ReactJs中處理事件的組件的狀態

[英]Changing the state of a component that isn't directly handling the event in ReactJs

為了更好地理解我的問題,請看一下我的組件圖: 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 
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM