将标题从React Native导航传递到标题组件

时间:2020-06-20 13:23:54

标签: javascript reactjs react-native

我试图将每个页面的标题从反应导航传递到标题组件,但是没有运气。我很确定我是核心发送该道具的,但是我不知道该如何使用{props.headerTitle},但没有运气。

标题组件:

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

导航

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

1 个答案:

答案 0 :(得分:1)

我不太确定您要完成什么。像这样设置标题选项时,默认情况下,React Navigation标头显示页面标题:

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

您在这里想要改变行为吗?

编辑:假设您尝试将标题传递给标题组件以进行进一步的自定义行为,则可以这样做:

// 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,
        }
    }}
/>

请参阅headerTitle上的文档:https://reactnavigation.org/docs/stack-navigator/#headertitle