【问题标题】:Dynamically change header title on react navigation 5.x在反应导航 5.x 上动态更改标题标题
【发布时间】:2020-09-16 17:16:15
【问题描述】:
我最近更新了我的项目以响应导航 5.x。
在早期版本中,我们使用如下设置标题标题:
static navigationOptions = ({ navigation }) => ({
title: 'find',
});
这不适用于 React Navigation 5.x。
请提出建议。
【问题讨论】:
标签:
javascript
reactjs
react-native
react-navigation
react-navigation-v5
【解决方案1】:
你可以通过2种方法做到这一点;
1:将options 设置为屏幕上的变量并保留当前代码:
<Stack.Screen
name="Label"
component={Component}
options={Component.navigationOptions}
/>
// component
static navigationOptions = {
title: 'find',
};
2:在您的组件中使用setOptions:
<Stack.Screen
name="News"
component={News}
options={{
title: 'Default',
}}
/>
// component
this.props.navigation.setOptions({title: 'find'});
【解决方案2】:
嘿,你一定要看看这个:https://reactnavigation.org/docs/screen-options-resolution/
在这里您可以看到如何为每个选项卡和每个堆栈设置标题。阅读扔页面,看看这个func:
function getHeaderTitle(route) {
// Access the tab navigator's state using `route.state`
const routeName = route.state
? // Get the currently active route name in the tab navigator
route.state.routes[route.state.index].name
: // If state doesn't exist, we need to default to `screen` param if available, or the initial screen
// In our case, it's "Feed" as that's the first screen inside the navigator
route.params?.screen || 'Feed';
switch (routeName) {
case 'Feed':
return 'News feed';
case 'Profile':
return 'My profile';
case 'Account':
return 'My account';
}
}