导航抽屉未打开且未找到 toggleDrawer

Navigation drawer is not opening and toggleDrawer not found

正在尝试使用 React-Navigation 创建抽屉。

使用 React Native 0.59,安装 React-Navigation 3.x,已完成链接 react-native link react-native-gesture-handler.

使用 React-Navigation 创建路线,名为 Route.js:

const Drawer = createDrawerNavigator(
  {
    Settings: {
      screen: HomeScene,
      navigationOptions: {
        title: 'Home',
        drawerIcon: () => (
          <Icon name="home" style={{ color: colors.white, fontSize: 24 }} type="Ionicons" />
        )
      }
    }
  },
  {
    contentComponent: props => <GlobalSideMenu {...props} />
  }
);

const AppNavigator = createStackNavigator(
  {
    Home: {
      screen: HomeScene,
      navigationOptions: {
        header: null
      }
    },
    Drawer: {
      screen: Drawer,
      navigationOptions: {
        header: null
      }
    }
  },
  {
    initialRouteName: 'Home'
  }
);

export default createAppContainer(AppNavigator);

然后在页眉、抽屉图标中:

 <Button icon transparent onPress={() => this.props.navigation.toggleDrawer()}>
      <Icon name={icon('menu')} type="Ionicons" style={styles.menuColor} />
 </Button>

它给我错误:toggleDrawer() 未定义。

那我改成:

this.props.navigation.dispatch(DrawerActions.toggleDrawer());

现在,没有错误,但抽屉打不开。

如果您试图从抽屉导航器的屏幕集外部打开抽屉,通常会出现这种情况。

this.props.navigation.toggleDrawer 仅在您处于 Settings 时才定义,我想情况并非如此。

您可以重新安排导航,使抽屉出现在您调用 toggleDrawer 的屏幕上,或者您可以先导航到 Settings

<Button
  icon 
  transparent 
  onPress={() => {
    this.props.navigation.navigate('Settings');
    this.props.navigation.dispatch(DrawerActions.openDrawer());
  }}
>
  <Icon name={icon('menu')} type="Ionicons" style={styles.menuColor} />
</Button>

Here is an example 澄清。