2017-05-25 60 views
2

我有一個嵌入了DrawerNavigator的屏幕。從導航器外部將參數發送到Drawer Navigator的contentComponent

import React, { Component } from "react"; 
import { GlobalNavigator } from "../navigators/globalNavigator"; 

export default class GlobalScreen extends Component { 
    constructor(props) { 
     super(props); 

     this.doSomething= this.doSomething.bind(this); 
    } 

    doSomething() { 
     // do something 
    } 

    render() { 
     return (
      <GlobalNavigator doSomething={this.doSomething} /> 
     ); 
    } 
} 

我有一個Drawer Navigator,其中指定了「contentComponent」。

import React from "react"; 
import { DrawerNavigator } from "react-navigation"; 
import MainScreen from "../screens/mainScreen"; 
import MenuContent from "../components/menuContent"; 

export const GlobalNavigator = DrawerNavigator(
    { 
     Main: { 
      screen: MainScreen 
     } 
    }, 
    { 
     drawerWidth: 350, 
     drawerPosition: "left", 
     initialRouteName: "Main", 
     backBehavior: "initialRoute", 
     contentComponent: props => <MenuContent {...props} /> 
    } 
); 

我想從屏幕發送一個參數到導航器,以便我可以將它傳遞給「contentComponent」。我怎樣才能做到這一點?我試着用 「screenProps」,但是這是不存在的 「道具」:contentComponent: props => <MenuContent {...props} />

回答

2

1.store的GlobalScreen instanse

import React, { Component } from "react"; 
import { GlobalNavigator } from "../navigators/globalNavigator"; 

var globalScreen = undefined; 

export default class GlobalScreen extends Component { 
    constructor(props) { 
     super(props); 
     globalScreen = this; 
     this.doSomething= this.doSomething.bind(this); 
    } 

    doSomething() { 
     // do something 
    } 

    //param to contentComponent 
    param = {abc:'123'}; 
    someMethod =()=>{ 
     //code 
    }; 

    render() { 
     return (
      <GlobalNavigator doSomething={this.doSomething} /> 
     ); 
    } 
} 

告訴上司contentComponent的方法道具來獲得globalScreen

export const GlobalNavigator = DrawerNavigator(
    { 
     Main: { 
      screen: MainScreen 
     } 
    }, 
    { 
     drawerWidth: 350, 
     drawerPosition: "left", 
     initialRouteName: "Main", 
     backBehavior: "initialRoute", 
     contentComponent: props => <MenuContent getMainScreen={() => {return globalScreen;} } {...props} /> 
    } 
); 

3.in MenuContent

let globalScreen = this.props.getMainScreen(); 
let param = globalScreen.param;//param you want to pass to menuContent 
globalScreen.someMethod();//method in globalScreen 

實現,但不是很優雅...... 。