DrawerNavigator在StackNavigator的标题内

时间:2019-01-11 13:11:20

标签: android reactjs react-native

我有一个DrawerNavigator

const Drawer = createDrawerNavigator({
  Home: { screen: Home},
  Profile: { screen: Profile}
});

我有一个看起来像这样的DrawerButton

const DrawerButton = (props) => {
  return (
    <View>
      <TouchableOpacity onPress={() => {props.navigation.navigate('DrawerOpen')}}>
        <Image
          source={require('../assets/buttons/menu.png')}
          style={{ width: 200, height: 80, resizeMode: 'contain' }}
        />
      </TouchableOpacity>
    </View>
  );
};

我有一个StackNavigator,可以在每个屏幕上更改navigationsOptions。

const AppRouteConfigs = createStackNavigator({
  Drawer: {
    screen: Drawer,    
  },
  Login: {
    screen: Login,
    navigationOptions: ({ navigation, screenProps }) => ({
      headerTransparent: true
    })
  },
  Home: {
    screen: Home,
    navigationOptions: ({ navigation, screenProps }) => ({
      headerStyle: {
        backgroundColor: colors.blue
      },
      headerTitle: <NavBarComponent />,
      headerRight:  <DrawerButton navigation={navigation} />,
      headerLeft: (
        <View style={{ padding: 15, paddingLeft: 10 }}>
          <Icon
            name="chevron-left"
            size={25}
            style={{ color: colors.white }}
            onPress={() => navigation.goBack()}
          />
        </View>
      )
    })
  });

我希望当我单击标题右侧时,将打开“抽屉”菜单。这行不通。当我单击它时,什么都没有发生。我正在使用React-Navigation 3.0.9navigation.goBack()函数,然后正确单击按钮(如果我将props.navigation.navigate('Home')分配给按钮的onPress()函数,它将按预期导航到该位置)。我正在使用Android设备进行测试。

我如何使它工作?

1 个答案:

答案 0 :(得分:1)

您不能在Drawer-Navigator中未定义的场景/屏幕中打开或关闭抽屉。

可以从其中定义的任何场景切换抽屉。因此,您应该在其中定义Home而不是像这样在StackNavigator中定义-

const Drawer = createDrawerNavigator({
  Profile: { screen: Profile}
  Home: {
    screen: Home,
    navigationOptions: ({ navigation, screenProps }) => ({
      headerStyle: {
        backgroundColor: colors.blue
      },
      headerTitle: <NavBarComponent />,
      headerRight:  <DrawerButton navigation={navigation} />,
      headerLeft: (
        <View style={{ padding: 15, paddingLeft: 10 }}>
          <Icon
            name="chevron-left"
            size={25}
            style={{ color: colors.white }}
            onPress={() => navigation.goBack()}
          />
        </View>
      )
    })
  }
});

const AppRouteConfigs = createStackNavigator({
  Drawer: {
    screen: Drawer,    
  },
  Login: {
    screen: Login,
    navigationOptions: ({ navigation, screenProps }) => ({
      headerTransparent: true
    })
  },
});

您还可以使用toggleDrawer提供的react-navigation功能来切换抽屉

const DrawerButton = (props) => {
  return (
    <View>
      <TouchableOpacity onPress={props.navigation.toggleDrawer}>
        <Image
          source={require('../assets/buttons/menu.png')}
          style={{ width: 200, height: 80, resizeMode: 'contain' }}
        />
      </TouchableOpacity>
    </View>
  );
};

希望有帮助。