Dynamically change header title on react navigation 5.x

对着背影说爱祢 提交于 2021-02-07 18:39:06

问题


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.


回答1:


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"
  component={Component}
  options={Component.navigationOptions}
/>

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

2: By using setOptions in your component:

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

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



回答2:


Hey you should definitly check out this: https://reactnavigation.org/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';
  }
}


来源:https://stackoverflow.com/questions/62080817/dynamically-change-header-title-on-react-navigation-5-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!