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

问题描述

我在React-Navigation中使用以下代码,其中使用Stack Navigation渲染屏幕。我有一个名为Header的自定义组件,该组件正在标题栏中渲染。我在Header组件本身中设置背景色。但是,如何使橙色背景覆盖整个宽度?这是外观的屏幕截图:

enter image description here

以下是我的导航代码

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;

以下是我的自定义标头组件中的代码

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,});

export default Header;

解决方法

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

,

对于高度,它是这样工作的

minHeight: '100%'

但对于宽度它不起作用

minWidth: '100%'