编程语言
首页 > 编程语言> > javascript – 使用React Navigation,如何强制抽屉导航器弹出到堆栈的顶部?

javascript – 使用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 />
      };
    }
  }
)

解决方法:

在我的项目中,我完全自定义了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因变量添加到标签中.

标签:javascript,react-native,react-navigation
来源: https://codeday.me/bug/20190701/1346706.html