在 React-Native 导航的 header 栏中呈现自定义 header 组件时出现问题

Issues with rendering a custom header component in the header bar of React-Native navigation

我在 React-Navigation 中使用以下代码,其中我使用 Stack Navigation 来呈现屏幕。我有一个名为 Header 的自定义组件,我正在 header 栏中呈现它。我在 Header 组件本身中设置背景颜色。但是我怎样才能让橙色背景覆盖整个宽度呢?这是它的外观截图:

以下是我的导航代码:

import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import Home from "../screens/Home";
import Detail from "../screens/Detail";
import Header from "../components/Header";

const Stack = createStackNavigator();
const HomeStack = () => {
  return (
    <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={Home}
        options={({ navigation }) => ({
          headerTitle: () => <Header navigation={navigation} />,
         
        })}
      />
      <Stack.Screen
        name="Detail"
        component={Detail}
        options={({ route }) => ({ title: route.params.title })}
      />
    </Stack.Navigator>
   </NavigationContainer>
  );
};

export default HomeStack;

以下是我的自定义 Header 组件中的代码:

const Header = ({ navigation, title }) => {
  const openMenu = () => {
    navigation.openDrawer();
  };
  return (
    <View style={styles.header}>
      <AntDesign
        name="menufold"
        style={styles.icon}
        size={28}
        color="black"
        onPress={openMenu}
      />
      <View style={styles.headerTitle}>
        <Text style={styles.headerText}>{title}</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  header: {
    width: "100%",
    height: "100%",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "tomato",
  },
  headerText: {
    fontWeight: "bold",
    fontSize: 20,
    color: "#fff",
    letterSpacing: 1,
  },
  icon: {
    position: "absolute",
    left: 16,
  },
  headerTitle: {
    height: 60,
    alignItems: "center",
    justifyContent: "center",
  },
});

export default Header;

您可以在Stack 的options 属性中提供Header Styles。 在您指定 headerTitle: () => <Header /> 自定义组件的选项中, 添加此 headerStyle : { backgroundColor: 'tomato' }

高度是这样的

minHeight: '100%'

但对于宽度它不起作用

minWidth: '100%'

一年后,我遇到了同样的问题... 就我而言,我需要为所有屏幕设置自定义 header,所以 screenOptions 对吗?

嗯,这行得通

<NavigationContainer>
    <Stack.Navigator
        screenOptions = {{
            header: (props) => <Header {...props} />,
        }}
    >
        <Stack.Screen name="Home" component={Home_post} />
    </Stack.Navigator>
</NavigationContainer>