You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native自定义导航栏如何仅在登录页隐藏、其余页面显示

实现方案

核心思路是监听当前路由名称,判断如果是登录页就不渲染自定义导航栏,其他页面正常渲染。

第一步:修改根目录App.js

import React, { useState, useRef } from 'react';
import { View, StyleSheet } from 'react-native';
import { NavigationContainer, DarkTheme } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import LoginScreen from './views/login'
import HomeScreen from './views/home'
import ProfileScreen from './views/profile'
import CustomNav from './views/nav/index'

const Stack = createStackNavigator();

export default function App() {
  // 创建导航实例引用
  const navigationRef = useRef();
  // 存储当前激活的路由名称
  const [currentRoute, setCurrentRoute] = useState('Login');

  return (
    <View style={styles.Test} >
      <NavigationContainer 
        ref={navigationRef}
        theme={DarkTheme} 
        linking={{
          config: {
            screens: {
              Login: "/",
              Home: "/home",
              Profile: "/Profile/:Username"
            }
          },
        }}
        // 路由变化时更新当前路由名称
        onStateChange={() => {
          const activeRoute = navigationRef.current.getCurrentRoute().name;
          setCurrentRoute(activeRoute);
        }}
      >
        <Stack.Navigator
          screenOptions={{
            headerShown: false
          }}
        >
          <Stack.Screen name="Login" component={LoginScreen} />
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Profile" component={ProfileScreen} />
        </Stack.Navigator>
        {/* 将当前路由传递给自定义导航组件 */}
        <CustomNav Nav="Mobile" currentRoute={currentRoute} />
      </NavigationContainer>   
    </View>
  );
}

const styles = StyleSheet.create({
  Test: {
    flex: 1
  }
})

第二步:修改./nav/index.js

import React from 'react';
import MobileNav from './mobile'
import WebsiteNav from './website'

// 接收父组件传递的当前路由参数
const CustomNav = ({ Nav, currentRoute }) => {
  // 登录页直接返回null,不渲染导航
  if (currentRoute === 'Login') {
    return null;
  }
  // 其他页面渲染对应端的导航
  return Nav === 'Mobile' ? <MobileNav /> : <WebsiteNav />;
}
  
export default CustomNav;

注意事项

  • 如果后续新增嵌套导航结构,需要调整getCurrentRoute()的逻辑获取最外层路由名称即可
  • 确保已安装@react-navigation/native、@react-navigation/stack等相关依赖

内容的提问来源于stack exchange,提问作者Volvic RBX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 07:39:02