使用React Navigation,如何强制抽屉式导航器弹出到堆栈顶部?

时间:2018-07-14 20:27:32

标签: javascript react-native react-navigation

我正在使用React Navigation,并且有一个抽屉式导航器,其中包含多个Stack Navigators作为其项目。当我打开抽屉导航器并单击一个项目时,它显示了我单击的堆栈中的第一个屏幕。当我转到堆栈中的第二个屏幕,然后打开抽屉并单击活动堆栈的相同抽屉链接时,我希望它显示堆栈的第一个屏幕,但是当前它什么都不做。我该如何实现?

这是显示问题的小吃:https://snack.expo.io/@zeckdude/navigation-demo

/**
 * Item Stack
 * Follows the Items Flow chart
 */
const ItemStack = createStackNavigator(
  {
    Items: { screen: ItemsScreen },
    Camera: { screen: CameraScreen },
    ViewItem: { screen: ViewItemScreen },
    AddEditItem: { screen: AddEditItemScreen },
  },
  {
    headerMode: 'none',
    navigationOptions: {
      gesturesEnabled: false,
    },
  }
);


/**
 * Send Stack
 * Follows the Send Flow chart
 */
const SendStack = createStackNavigator(
  {
    Send: { screen: SendScreen },
    ScanQR: { screen: ScanQRScreen },
    SendConfirmation: { screen: SendConfirmationScreen },
  },
  {
    headerMode: 'none',
    navigationOptions: {
      gesturesEnabled: false,
    },
  }
);


/**
 * Authorized Drawer
 * Used to set the labels in the drawer and enable drawer
 */
const AuthorizedDrawer = createDrawerNavigator(
  {
    ScanQR: { 
      screen: ScanQRScreen,
      navigationOptions: {
        drawerLabel: 'Scan'
      } 
    },
    ItemStack: { 
      screen: ItemStack,
      navigationOptions: {
        drawerLabel: 'Items'
      }
    },
    SendStack: { 
      screen: SendStack,
      navigationOptions: {
        drawerLabel: 'Send'
      } 
    },
  },
  {
    initialRouteName: 'ItemStack'
  }
);


/**
 * Authorized Drawer Stack
 * Put the drawer inside a stack so the header can be added and styled
 */
const AuthorizedDrawerStack = createStackNavigator(
  {
    AuthorizedDrawer: { screen: AuthorizedDrawer },
  }, 
  {
    headerMode: 'float',
    navigationOptions: ({navigation, screenProps, navigationOptions}) => {
      return {
        headerLeft: (
          <View 
            style={{
              paddingLeft: 10,
            }}
          >
            <Icon 
              name={navigation.state.isDrawerOpen ? 'close' : 'menu'}
              color="#2F6BAE"
              onPress={() => {
                navigation.toggleDrawer();
              }} 
            />
          </View>
        ),
        headerTitle: <Logo />
      };
    }
  }
)

1 个答案:

答案 0 :(得分:2)

在我的项目中,我完全自定义了contentComponent:

const DrawerNavigator = createDrawerNavigator({
  screens, stacks etc...
}, {
    contentComponent: SideMenu,
    ...
})

SideMenu只是带有导航按钮的简单组件。因此,我已经在自定义组件中实现了每个onPress函数。他们只是这样导航到相关堆栈的初始屏幕:

onPress = () => {
 this.props.navigation.dispatch(DrawerActions.closeDrawer()); 
 this.props.navigation.navigate('TheInitialScreenInTheStack')
}

它在React Navigation 2中对我有用。在其他方面,例如从抽屉登录和注销或向选项卡添加redux因变量,它对我也非常有帮助。