如何将params传递给DrawerNavigator?

时间:2018-01-09 16:11:36

标签: react-native react-navigation

TL D R:我有一个登录屏幕,用户登录并导航到第二个屏幕。在那里,我想打开菜单,并将用户名显示为文本。如何将用户名传递给菜单? (DrawerNavigator)。

我的代码的一些示例如下。

路由器:

import MyMenu from './MyMenu';

const MyStack = StackNavigator({
  Login: {screen: Login},
  Home: {screen: Home}
  // more screens...
});

export const MyDrawer = DrawerNavigator({
  Main: { screen: MyStack }
},
  { contentComponent: MyMenu }
);

主屏幕:

openMenu() {
  this.props.navigation.navigate('DrawerOpen', userName);
}

MyMenu菜单:

render() {
  const userName = this.props.navigation.state.params;
  return (
    <View>
          <Text>{userName}</Text>
          // more stuff
    </View>
  );
}

3 个答案:

答案 0 :(得分:2)

I think this is what you want.

import MyMenu from './MyMenu';

const MyStack = StackNavigator({
  Login: {screen: Login},
  Home: {screen: Home}
  // more screens...
});

export const MyDrawer = DrawerNavigator({
  Main: { screen:({navigation}) => <MyStack screenProps={drawerNavigation:navigation}/> }
},
  { contentComponent: MyMenu }
);

Then you can access drawer's navigation from your Stack navigation like below.

this.props.screenProps.drawerNavigation.DO_WHATEVER

答案 1 :(得分:0)

您需要将道具传递给MyMenu组件:

路由器:

    export const MyDrawer = DrawerNavigator({
      Main: { screen: MyStack }
    },
      { contentComponent: (props) => <MyMenu {...props} /> }
    );

主屏幕:

openMenu() {
  this.props.navigation.navigate('DrawerOpen', {userName: userName});
}

答案 2 :(得分:0)

好的,在花了这么多时间之后,我终于找到了解决方案。 简而言之,您只能在导航到新屏幕时发送导航道具 - “DrawerOpen”不计入此内容。

要解决这个问题,我必须稍微改变一下结构,而不是将DrawerNavigator作为根抽屉,我有一个StackNavigator作为根抽屉。

在:

const MyStack = StackNavigator({
  Login: {screen: Login},
  Home: {screen: Home}
  // more screens...
});

export const MyDrawer = DrawerNavigator({
  Main: { screen: MyStack }
},
  { contentComponent: MyMenu }
);

后:

const MyStack = StackNavigator({
  Home: {screen: Home},
  // more screens...
});

const MyDrawer = DrawerNavigator({
  Main: { screen: MyStack }
},
  { contentComponent: MyMenu }
);

export const RootStack = StackNavigator({
  Login: {screen: Login},
  Drawer: {
     screen: MyDrawer,
     navigationOptions: { header: null } } //prevent double header
});

现在在登录屏幕中,我会像这样导航到抽屉:

_login() {
    this.props.navigation.navigate('Drawer', { userName: userName });
}

最后在MyMenu(这是'抽屉'的一部分):

render() {
  const { userName } = this.props.navigation.state.params;
  return (
    <View>
          <Text>{userName}</Text>
          // more stuff
    </View>
  );
}

有效!