首页 > 解决方案 > React Navigation v5 使用自定义标头

问题描述

如果我在 React-Navigation V5 中将标头设置为关闭,是否可以使用自定义标头?

我试过了,但是headerLeftandheaderRight似乎什么也没做,例如,我有以下内容:

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

然后在我的UploadStack,我有

<Stack.Navigator initialRouteName="TrackUploadSelectionScreen">
      <Stack.Screen
        name="AddToPlaylistScreen"
        component={AddToPlaylistScreen}
      />
      <Stack.Screen
        name="TrackUploadSelectionScreen"
        component={TrackUploadSelectionScreen}
        options={{
          title: t('general.selectToUpload'),
          headerLeft: () =>
            Platform.select({
              ios: () => (
                <NavigationHeader.TextButton
                  label={t('general.cancel')}
                  onPress={navigation.goBack()}
                />
              ),
              android: () => (
                <NavigationHeader.IconButton
                  iconName="times"
                  label={t('general.cancel')}
                  onPress={navigation.goBack()}
                />
              )
            })
        }}
      />
</Stack.Navigator>

但它没有创造任何东西

标签: react-nativereact-navigation

解决方案


如果您设置headerShown为,和属性设置的false所有内容,则不会显示。因此,如果您确实想设置这些属性中的任何一个,请删除该行。headerLeftheaderRightheader

此外,如果您想要自定义标题,而不是默认栏,您可以简单地设置header属性。这是一个自定义标题的示例,其中删除了栏,但是使用 flexbox 在左侧和右侧放置了 2 个非常简单的按钮。

// ...
<Stack.Screen
  options={{
    header: () => (
      <View
        style={{
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
          height: 50,
        }}>
        <TouchableOpacity
          style={{ padding: 10 }}
          onPress={() => {
            alert('Left');
          }}>
          <Text>Left</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={{ padding: 10 }}
          onPress={() => {
            alert('Right');
          }}>
          <Text>Right</Text>
        </TouchableOpacity>
      </View>
    ),
  }}
  // Other props...
/>
// ...

您可以调整样式和内容以满足您的需求。


推荐阅读