2016-12-31 62 views
-1

在NavigatorIOS中有一個2層深的按鈕,當觸發時,應該改變TabBarIOS選中的TabBarIOS項。孫子組件不改變祖父母狀態

的組件的結構如下:
--FooterTabs
------ NavigatorIOS:列表 - >列表項

我試圖通過具有內部FooterTabs一個函數來做到上述改變所述狀態,並且當狀態的'selectedTab'===不同的字符串時,TabBar.Items的prop'selected'變爲true。

像這樣:

_changeToAlarms(){ 
    console.log('Hello from Footer Tabs'); 
    this.setState({ 
     selectedTab: 'Alarms' 
    }); 
    } 

render(){ 
    return(
    <Icon.TabBarItemIOS title={'Alarms'} 
       iconName='ios-clock' 
       selected={this.state.selectedTab === 'Alarms'} 
       onPress={()=> { 
       this.setState({ 
        selectedTab: 'Alarms' 
       }); 
       }}> 
       <ComingSoon/> 
      </Icon.TabBarItemIOS> 

<Icon.TabBarItemIOS title={'Schedules'} 
        iconName='ios-moon' 
        selected={this.state.selectedTab === 'Schedules'} 
        onPress={()=> { 
        this.setState({ 
         selectedTab: 'Schedules' 
        }); 
        }}> 
       </Icon.TabBarItemIOS> 
); 
} 

* Icon.TabBatItem行爲酷似TabBarIOS.Item。

onPress工作,但能夠以類似的方式(通過修改組件的狀態)改變選項卡我通過_changeToAlarms()作爲'SleepSchedules'的道具。

<Icon.TabBarItemIOS ... 
        > 
        <NavigatorIOS 
        initialRoute={{ 
         component: SleepSchedules , 
         title: ' ', 
         passProps: {changeToAlarms:()=> this._changeToAlarms()} 
        }} 
        style={{flex: 1}} 
        /> 
       </Icon.TabBarItemIOS> 

而且從SleepSchedules,我導航到下一個組件並傳遞previous'changeToAlarms'作爲道具。

_handlePress(selectedSchedule){ 
    this.setState({selectedSchedule}); 

    this._navScheduleItem(selectedSchedule) 
    } 

    _navScheduleItem(scheduleName){ 

    this.props.navigator.push({ 
     title: `${scheduleName} Sleep`, 
     component: ScheduleItem, 
     passProps: {scheduleName}, changeToAlarms:()=> this.props.changeToAlarms 
    }) 
    } 

render(){ 
    return(
     ... 
     onPress={()=> this._handlePress('Monophasic')}> 
    ); 
} 

而且在ScheduleItem我試圖打電話給道具「changeToAlarm」已傳遞,這應該是從頁腳標籤之一。

_handleTouch(){ 
    console.log('Hello from Schedule Item'); 
    this.props.changeToAlarms; 
} 

render(){ 
    return(
     ... 
     onPress={()=> this._handleTouch()} 
    ); 
} 

控制檯登錄「你好從ScheduleItem」每次我按下它的時候,但不記錄「從FooterTabs你好」,也沒有改變的標籤。

有沒有人發現錯誤?

我是初學者,非常感謝您的幫助! :)

+0

我不知道這是否是解決問題的正確方法,但這是我對它的概念。如果我的方法有任何錯誤,請隨時評論正確的方法。 –

回答

0

你需要一個()this.props.changeToAlarms之後。 this.props.changeToAlarms()

0

我認爲可能有更好的方法,但沒有看到更多的代碼很難得到正在發生的事情的全貌。在你的_handlePress函數中,確實吸引了我的注意力。你調用setState然後調用另一個函數。

根據ReactDocs

沒有來電的同步運行的保證SETSTATE ,呼叫可能會分批進行性能提升。

這可能會導致您的問題,再次沒有更多的代碼很難說。您可以嘗試將overload method用於setState,該函數將函數作爲第二個參數。

setState(nextState,回調) 執行nextState到當前狀態的淺合併。這是您用來從事件處理程序和服務器請求>回調觸發UI更新的主要方法。

第一個參數可以是一個對象(包含零個或多個到 更新的鍵)或一個函數(狀態和道具),它返回包含要更新的鍵的對象 。

這將確保在執行你的下一個功能之前,你setstate這完成。

_handlePress(selectedSchedule){ 
    this.setState({selectedSchedule},() => 
    { 
     this._navScheduleItem(selectedSchedule); 
    }); 
    } 
相關問題