如何从本机应用程序的构造函数中更改navigationOptions中的标题标题?

GAU*_*RAV 6 reactjs react-native react-native-drawer react-native-tab-view react-native-tabnavigator

在我的本机项目中,我使用了DrawerNavigator,从中我导航到SwitchAccount页面。在SwitchAccount页面中,我使用了react-native-tabs中的Tabs。下面是我使用的代码

    render() {
      return (
     <View style={[styles.container]}>
      // Here _renderTab function return component based on selectedService
      {this._renderTab(this.state.selectedService)} 
      <TabBarContainer
          selectedService={this.state.selectedService}
          onTabChange={this._switchService}
        />
     </View>
    ); 
  }
Run Code Online (Sandbox Code Playgroud)

当我单击选项卡时,它会更改状态,然后获得_renderTab函数返回的新组件。一切正常,但我想基于_renderTab函数返回的组件更改Header标题。我该怎么办?有什么办法可以从构造函数更改标题标题吗?以下是我在SwitchAccount页面中的navigationOptions的代码。在那里,我想从构造函数更改标题。

    static navigationOptions = {
    title:'Filter',
    drawerLabel: 'Switch Account',
    drawerIcon: ({ tintColor }) => (
      <Icon
        name='md-switch'
        size={40}
        color='black'
      />
    ),
  };
Run Code Online (Sandbox Code Playgroud)

jua*_*rco 5

一种方法是使用导航paramsnavigationOptions可以定义为一个函数(而不是对象),该函数接收包含navigation对象本身的对象作为其键之一:

static navigationOptions = ({navigation}) => ({ /* ... */ })
Run Code Online (Sandbox Code Playgroud)

这使您可以通过从navigation对象读取参数来动态设置标题:

static navigationOptions = ({navigation}) => ({
    title: navigation.getParam('title', 'DefaultTitle'),
    /* ... */
})
Run Code Online (Sandbox Code Playgroud)

然后,您可以在其中一个组件中调用对象setParams上的navigation函数来设置标题:

handleChangeTab = (tab) => {
    /* Your tab switching logic goes here */

    this.props.navigation.setParams({
        title: getTitleForTab(tab)
    })
} 
Run Code Online (Sandbox Code Playgroud)

请注意,必须已安装了组件才能react-navigation访问navigation道具,否则,您将不得不从其父项传递它,或者使用withNavigationHoC封装该组件并使其从那里接收道具。

就是说,您考虑过使用Tab导航吗?