最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically change header title on react navigation 5.x - Stack Overflow

programmeradmin8浏览0评论

I have recently updated my project to react navigation 5.x. In earlier version we used to set header title as follows :

static navigationOptions = ({ navigation }) => ({
        title: 'find',
});

This is not working on React Navigation 5.x. Please Suggest.

I have recently updated my project to react navigation 5.x. In earlier version we used to set header title as follows :

static navigationOptions = ({ navigation }) => ({
        title: 'find',
});

This is not working on React Navigation 5.x. Please Suggest.

Share Improve this question edited May 29, 2020 at 9:59 yesIamFaded 2,0683 gold badges25 silver badges50 bronze badges asked May 29, 2020 at 7:28 RizwanRizwan 3,6863 gold badges18 silver badges41 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 16

You can do it via 2 methods;

1: Set options to be a variable from your screen and keep your current code:

<Stack.Screen
  name="Label"
  ponent={Component}
  options={Component.navigationOptions}
/>

// ponent
static navigationOptions = {
  title: 'find',
};

2: By using setOptions in your ponent:

<Stack.Screen
  name="News"
  ponent={News}
  options={{
    title: 'Default',
  }}
/>

// ponent
this.props.navigation.setOptions({title: 'find'});

After going through various SO posts and documents I found the following ways to do this -

In the Component using setOptions

this.props.navigation.setOptions({title: 'TitleSetInComponent'});

Can also give a default title in createStackNavigator();

<Stack.Screen
  name="myComponent"
  ponent={MyComponent}
  options={{
    title: 'TitleSetInStackNavigator',
  }}
/>

In createStackNavigator(); using navigationOptions as options

<Stack.Screen
name="myComponent"
ponent={MyComponent}
options={MyComponent.navigationOptions}
/>

// MyComponent
static navigationOptions = {
title: 'TitleSetInComponent',
};

Hey you should definitly check out this: https://reactnavigation/docs/screen-options-resolution/

Here you can see how to set the title for each tab and each stack. Read threw the page and look at this 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';
  }
}
发布评论

评论列表(0)

  1. 暂无评论