首页 > 解决方案 > 使用 headerMode 浮动在特定屏幕中隐藏自定义标题

问题描述

我的应用中有 3 个屏幕:“主页、联系人、个人资料”。我创建了一个自定义标题以显示在主页和联系人中,但不在个人资料屏幕中。问题是:我的自定义标题没有隐藏在配置文件屏幕中。如果我删除我的自定义标头以使用默认标头,它会隐藏,但是当我回到我的自定义标头时,这不会发生。

应用程序.js

       <NavigationContainer ref={navigationRef}>
            <Stack.Navigator
            headerMode="float"
            initialRouteName="Home"
            screenOptions={{ 
                header: props => <CustomHeader {...props} />
            }}>

                <Stack.Screen
                name="Home"
                component={Home}
                options={{
                    cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS    
                }}/>

                <Stack.Screen name="Contacts" component={Contacts}
                options={{
                    cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS    
                }}/>

                <Stack.Screen
                name="Profile"
                component={Profile}
                options={{
                    headerShown: false
                }} />  

            </Stack.Navigator>
        </NavigationContainer>

标签: react-nativereact-navigationreact-native-navigationreact-navigation-stackreact-navigation-v5

解决方案


You can provide screen wise header like.

<NavigationContainer ref={navigationRef}>
  <Stack.Navigator
    headerMode="float"
    initialRouteName="Home">
    <Stack.Screen
      name="Home"
      component={Home}
      options={{
        cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: (props) => <CustomHeader {...props} />
      }}
    />

    <Stack.Screen
      name="Contacts"
      component={Contacts}
      options={{
        cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: (props) => <CustomHeader {...props} />
      }}
    />

    <Stack.Screen
      name="Profile"
      component={Profile}
      options={{
        headerShown: false,
        header: null,
      }}
    />
  </Stack.Navigator>
</NavigationContainer>;

Or you can create custom function for all header

function getHeader(route, props) {
  const routeName = route.state
    ?
      route.state.routes[route.state.index].name
    : || 'Home';

  switch (routeName) {
    case 'Home':
    case 'Contacts':
      return <CustomHeader {...props} />
    case 'Profile':
      return null;
  }
}

and use it like


 <Stack.Screen
      name="Profile"
      component={Profile}
      options={({ route }) => ({
        header: (props)=> getHeader(route, props),
      })}
    />

Source : https://reactnavigation.org/docs/screen-options-resolution


推荐阅读