简体   繁体   中英

Passing title from React Native navigation to Header Component

I m trying to pass the title of each page from react navigation to the header component but with no luck. I am pretty sure that i am sending the prop corectly but i dont know how to used i tried with {props.headerTitle} but no luck.

Header Component:

export default function Header() {
  return (
    <View style={styles.header}>
      <Text>{props.headerTitle}</Text>
    </View>
  );
}

Navigation

<AuthStack.Navigator initialRouteName={RegisterLogin}>
            <AuthStack.Screen
              name="RegisterLogin"
              component={RegisterLogin}
              options={({navigation, route}) => ({
                headerShown: false,
                headerTitle: (props) => <Header {...props} />,
                headerStyle: {
                  backgroundColor: 'red',
                  elevation: 0,
                  shadowOpacity: 0,
                  borderBottomWidth: 0,
                },
              })}
            />
            <AuthStack.Screen
              name="Login"
              component={LoginWithContext}
              options={({navigation, route}) => ({
                headerTitle: (props) => <Header {...props} />,
                headerStyle: {
                  backgroundColor: 'red',
                  elevation: 0,
                  shadowOpacity: 0,
                  borderBottomWidth: 0,
                },
              })}
            />

I'm not quite sure what you're trying to accomplish. React Navigation headers display the page title by default when you set the title option like so:

<AuthStack.Screen
    name="RegisterLogin"
    component={RegisterLogin}
    options={{
        title: 'Your title here',
        headerStyle: {
            backgroundColor: 'red',
            elevation: 0,
            shadowOpacity: 0,
            borderBottomWidth: 0,
        }
    }}
/>

Is there a different behavior you want here?

Edit: assuming you are trying to pass the title to your header component for some further custom behavior, you can do it like so:

// Header Component
function Header({children}) {
    return (
        <View>
            <Text>{children}</Text>
        </View>
    );
}
// In your navigator
<AuthStack.Screen
    name="RegisterLogin"
    component={RegisterLogin}
    options={{
        title: 'Your title here',
        headerTitle: (children) => <Header {...children}/>,
        headerStyle: {
            backgroundColor: 'red',
            elevation: 0,
            shadowOpacity: 0,
            borderBottomWidth: 0,
        }
    }}
/>

See the docs on headerTitle : https://reactnavigation.org/docs/stack-navigator/#headertitle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM