2017-12-18 121 views
0

我想在我的反應導航標題中調用自定義按鈕內的自定義函數。我看着周圍的幾個方法可以做到這一點,我已經找到了最好的結果是使功能靜態的,那就是:但是標題按鈕內部自定義函數反應原生

export class MyClass extends React.Component{ 
    static navigationOptions = ({navigation}) => ({ 
     headerRight: (<Button title='press me' onPress={()=> MyClass.SomeFunction() } ></Button>) 
    }); 
    static SomeFunction(){ 
     /*Some code here*/ 
    } 
    /*Some extra code here*/ 
} 

我的問題是,我需要內部訪問一些國家性質SomeFunction(),如您所知,您無法在靜態函數中訪問this

有沒有什麼辦法可以訪問一個靜態內的組件的狀態,還是有一個更好的方法來實現一個自定義函數在一個按鈕中的頭?

+0

無需使該功能靜態化。 –

回答

0

作爲替代解決方案,您可以設置導航器狀態以設置和獲取值。

如果使用AppWithNavigation狀態父爲您的導航結構的根,你應該是一個navigation道具傳遞給子元素象下面這樣:

render() { 
    const { dispatch, nav, } = this.props 
    return (
     <AppNavigator 
      navigation={addNavigationHelpers({ 
       dispatch: dispatch, 
       state: nav, 
      })} 
     /> 
    ) 
} 

如果是這樣,只需使用下面的行設置你的價值觀:

this.props.navigation.state.someValue 

this.props.navigation.setParams({someValue: 'Value'}) 

每當你想要像下面然後讓你的設定值

或者

const { someValue } = this.props.navigation.state 

但請記住,當第一次呈現組件的狀態可以爲空或未定義。所以,你需要檢查其現有之前嘗試獲得:

if (!this.props.navigation.state) { 
    return null 
} 

const someValue = this.navigation.state.someValue 

if (someValue) { 
    /* you can use your someValue here! */ 
} 

注到每個航線都有自己的狀態對象。當你的屏幕被改變時,你的this.props.navigation.state對象的狀態被改變。如果您需要全球解決方案,我認爲您可以使用Redux。

0

經過一段時間的代碼搞亂之後,我發現了一個更適合我需求的解決方案。我將它張貼在下面以防萬一。謝謝大家的貢獻:D

export class MyClass extends React.Component{ 
    static navigationOption = ({navigation}) => ({ 
     headerRight: (<Button title='Press Me!' onPress={() => MyClass.SomeFunc() }) 
    }) 

    //The function 
    static SomeFun(){ 
     alert(MyClass.SomeState.abc) 
    } 

    //Static functioning as state 
    static SomeState = { 
     abc: 'def' 
    } 
}