React Navigation 初探 - 配置标题栏
设置标题
Screen
组件接收一个 options
属性, 它是一个对象或一个返回对象的函数. 它包含了各种配置项, 比如我们用于设置标题的 title
.
function StackScreen() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'My home' }}
/>
</Stack.Navigator>
);
}
在标题中使用参数
为了在标题中使用参数,我们让屏幕的 options
成为一个返回配置的函数. 它可能诱导你使用 this.props
中的 options
, 但是因为他是在组件定义之前定义的, this
不是组件实例,没有可用的 props
. 相反, 如果我们定义一个 options
方法, React Navigation
将通过带有 { navigation, route }
参数调用它, 这种情况下,我们只需要关心 route
, 他与传递到你页面的 route
属性是同一对象. 我们可以通过 route.params
获取参数, 通过他获取附加参数,并设置为标题.
function StackScreen() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'My home' }}
/>
<Stack.Screen
name="Profile"
component={ProfileScreen}
options={({ route }) => ({ title: route.params.name })}
/>
</Stack.Navigator>
);
}
传递给 options
的方法包含两个参数:
navigation
: 当前页面导航器route
: 导航路由
通过 setOptions
更新 options
我们通常需要在当前页面修本身的 options
.可以通过 navigation.setOptions
实现.
/* Inside of render() of React class */
<Button
title="Update the title"
onPress={() => navigation.setOptions({ title: 'Updated!' })}
/>
调整标题样式
可以通过三个属性定义你的导航栏样式: headerStyle
, headerTintColor
, headerTitleStyle
.
headerStyle
: 设置导航栏样式. 如果你设置了backgroundColor
,你的导航栏就是相应颜色.headerTintColor
: 设置标题和按钮的颜色.headerTitleStyle
: 给title
设置fontFamily
,fontWeight
以及其他样式.
function StackScreen() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
title: 'My home',
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}}
/>
</Stack.Navigator>
);
}
options
跨屏共享
通常我们希望多个页面有类似的导航栏. 可以通过设置 native stack navigator
的 screenOptions
属性,实现多页面共享.
function StackScreen() {
return (
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}}
>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'My home' }}
/>
</Stack.Navigator>
);
}
通过自定义组件替换 title
有的时候我们不仅仅需要修改 title
的文字和样式,还会添加一些操作.例如: 在标题为题渲染一个图片或者显示一个 button 按钮. 你可以自定义组件覆盖标题组件.
function LogoTitle() {
return (
<Image
style={{ width: 50, height: 50 }}
source={require('@expo/snack-static/react-native-logo.png')}
/>
);
}
function StackScreen() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ headerTitle: props => <LogoTitle {...props} /> }}
/>
</Stack.Navigator>
);
}
你也许会好奇,我们为什么不像之前一样提供一个
title
组件而提供一个headerTitle
组件,headerTitle
是native stack navigator
一个特殊的属性, 他默认是一个Text
组件展示title
.