React Native 条件渲染页眉和页脚

cunj1qz1  于 2023-10-22  发布在  React
关注(0)|答案(1)|浏览(119)

我正在开发一个react原生应用程序,我想只在某些屏幕上显示页眉和页脚,而在其余的屏幕上,我想隐藏它们。我们如何才能实现这一目标?

export default function Router() {
  const {isLoggedIn, isLogoutPressed} = useContext(AppContext);

  return (
    <NavigationContainer>
      {isLoggedIn ? (
        <>
          <Header />
          <AppStack />
          <FooterNavBar />
          {isLogoutPressed && <LogoutModal />}
        </>
      ) : (
        <AuthStack />
      )}
    </NavigationContainer>
  );
}

我已经尝试这样做,但我得到的错误

export default function Router() {
  const {isLoggedIn, isLogoutPressed} = useContext(AppContext);
  const route = useRoute();

  const shouldRenderHeader = () => {
    // Check if the current route name is one of the screens where you want to show the header
    const allowedScreens = ['HomeScreen', 'ProfileScreen', 'Profile'];
    return allowedScreens.includes(route.name);
  };

  return (
    <NavigationContainer>
      {isLoggedIn ? (
        <>
          <Header />
          {shouldRenderHeader(route) && <Header />}
          <AppStack />
          <FooterNavBar />
          {isLogoutPressed && <LogoutModal />}
        </>
      ) : (
        <AuthStack />
      )}
    </NavigationContainer>
  );
}

错误:

错误:找不到路由对象。你的组件在导航器的屏幕里吗?
此错误位于:在Router(由App创建)中在AppProvider(由App创建)中在App中在RCTView(由View创建)中在View(由AppContainer创建)中在RCTView(由View创建)中在View(由AppContainer创建)中在AppContainer中

svdrlsy4

svdrlsy41#

使用onStateChange监听导航状态的变化,并基于此修改应用程序状态以隐藏/显示组件。大概是这样的:

const [showHeader, setShowHeader] = useState(true)

<NavigationContainer 
  onStateChange={({routes}) => setShowHeader(routes[routes.length - 1].name == 'Home')}>
  {showHeader && <Header/>}
  <Stack.Navigator
    screenOptions={{
      headerShown: false
    }}>
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Detail" component={DetailScreen} />
  </Stack.Navigator>
</NavigationContainer>

相关问题