1

我有一个抽屉导航配置如下:

const CustomDrawerContent = () => { return ( <DrawerItem label="Log out2" onPress={() => logOut()} /> ) }

  const loginStack = () => (
    <Stack.Navigator >
      <Stack.Screen name='LandingScreen' component={LandingScreen} options={{headerShown: false}} />
      <Stack.Screen name='LoginScreen' component={LoginScreen} options={{headerShown: false}} />
      <Stack.Screen name='RegisterScreen' component={RegisterScreen} options={{headerShown: false}} />
    </Stack.Navigator>
  )

  return (
    <NavigationContainer>
      <Drawer.Navigator
      screenOptions={{
        drawerStyle: { backgroundColor: 'white' },
        drawerPosition: 'right'
      }}>

        {!user ? (
          <Drawer.Screen
            name="PublicStack"
            component={loginStack}
            options={{headerShown: false}}
          /> )
        :
        (<>
          <Drawer.Screen name='Search cocktails' component={HomeScreen} options={{ header: () => <Header/> }} />
          <Drawer.Screen name='Profile' component={ProfileScreen} options={{ header: () => <Header/> }} />
          <Drawer.Screen name='Publish a recipe' component={PublishRecipeScreen} options={{ header: () => <Header/> }} />
          <Drawer.Screen name='Favorites' component={FavoritesScreen} options={{ header: () => <Header/> }} />
          <Drawer.Screen name='Published recipes' component={PublishedRecipesScreen} options={{ header: () => <Header/> }} />
          <Drawer.Screen name='Log out' component={CustomDrawerContent} options={{ header: () => <Header/> }} />

          <Drawer.Screen name='CocktailDetailScreen' component={CocktailDetailScreen} options={{
            header: () => <Header/>,
            drawerLabel: () => null,
            title: undefined
          }} />
        </>
        )}

      </Drawer.Navigator>
    </NavigationContainer>
  )

所有屏幕都可以正常工作,但我想Log out在按下时执行注销功能。据我了解,我不能直接在屏幕组件上添加这个事件监听器,所以我按照这个文档(https://reactnavigation.org/docs/drawer-navigator/#drawercontent)并尝试了一些不同的东西:

  • 我创建了CustomDrawerContent一个DrawerItem.
  • 如果我CustomDrawerContent作为组件传递到Log out屏幕(就像现在的代码一样),当我点击它时,我会被重定向到一个呈现CustomDrawerContent组件的空白页面,这不是我想要的。
  • 如果我 CustomDrawerContent作为drawerContent道具传递给抽屉导航器,就像文档说的(下面的示例),所有其他屏幕都不再呈现,这又不是我想要的。
<Drawer.Navigator drawerContent={(props) => <CustomDrawerContent />}>
  {/* screens */}
</Drawer.Navigator>
  • 如果我将抽屉项目与导航器内的屏幕放在一起,应用程序会抛出以下错误:
useNavigationBuilder.tsx:134 Uncaught Error: A navigator can only contain 'Screen', 'Group' or 'React.Fragment' as its direct children (found 'DrawerItem'). To render this component in the navigator, pass it in the 'component' prop to 'Screen'.

那么如何在不“覆盖”屏幕的情况下将项目添加到抽屉中呢?还是有其他方法可以在抽屉中放置一个简单的注销按钮?

完整代码可以在这里找到:https ://github.com/coccagerman/mixr

4

0 回答 0