在react导航 5.x 上动态更改标题标题

IT技术 javascript reactjs react-native react-navigation react-navigation-v5
2021-05-11 20:33:09

我最近更新了我的项目以响应导航 5.x。在早期版本中,我们曾经设置标题标题如下:

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

这不适用于 React Navigation 5.x。请建议。

2个回答

您可以通过 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'});

嘿,你一定要看看这个:https : //reactnavigation.org/docs/screen-options-resolution/

在这里您可以看到如何为每个选项卡和每个堆栈设置标题。阅读抛出页面并查看此功能:

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';
  }
}