React-Navigation在tabNavigation上显示动态标题

时间:2018-08-24 10:32:42

标签: reactjs react-native react-navigation

我有此代码:

import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import HomeScreen from './modules/Home/HomeScreen';
import DetailScreen from './modules/Home/DetailScreen';
import React from 'react';

const tabNav = createBottomTabNavigator(
    {
        Home: {
            screen: HomeScreen,
        },
        Details: { screen: DetailScreen },
    },
);
//
tabNav.navigationOptions = ({ navigation }) => {
    let { routeName } = navigation.state.routes[navigation.state.index];
    console.log('navigation: ', navigation.state);
    let title;
    if (routeName === 'Home') {
        title = 'Home';
    } else if (routeName === 'Details') {
        title = 'Detail';
    }
    return {
        title,
        headerMode: 'none',
    };
};
//

const RootNavigator = createStackNavigator(
    {
        Main: tabNav,
    },
    {
        navigationOptions: {
            headerMode: 'none',
            headerTransparent: true,
        },
    },
);

export default RootNavigator;

此代码运行良好。

jQuery documentation on the function keypress()

我的问题是,我想将此部分更改为动态。我尝试将stackNavigator放在标签中,但始终向我返回错误。

if (routeName === 'Home') {
    title = 'Home';
} else if (routeName === 'Details') {
    title = 'Detail';
}

有什么建议吗?


更新:

我试图将stackNavigator放在屏幕中:

const tabNav = createBottomTabNavigator(
    {
        Home: createStackNavigator({
            screen: HomeScreen,
            navigationOptions: {
                title: 'Home 2',
            },
        }),

        Details: { screen: DetailScreen },
    },
);

它不断回报我The component for route 'navigationOptions' must be a React component.

1 个答案:

答案 0 :(得分:3)

StackNavigator配置错误,请尝试以下操作:

const tabNav = createBottomTabNavigator({
    Home: {
        screen: createStackNavigator({
            homeSreen: {
                screen: HomeScreen,
                navigationOptions: {
                    title: 'Home 2',
                },
            },{
                initialRouteName: 'homeScreen',
        })
    },
    Details: { screen: DetailScreen },
});

const HomeStack = createStackNavigator({
    home: {
      screen: HomeScreen,
      navigationOptions: {
        title: 'Home 2',
      },
    },
  },{
      initialRouteName: 'home',
  });

 const tabNav = createBottomTabNavigator({
    Home: { screen: HomeStack },
    Details: { screen: DetailScreen },
 });

https://reactnavigation.org/docs/en/stack-navigator.html

您可以设置每个屏幕的标题:

const tabNav = createBottomTabNavigator(
    {
        Home: {
            screen: HomeScreen,
            navigationOptions: {
                title: 'Home',
            },
        },
        Details: {
            screen: DetailScreen,
            navigationOptions: {
                title: 'Details',
            },
        },
    },
);

https://reactnavigation.org/docs/en/tab-navigator.html#navigationoptions-for-screens-inside-of-the-navigator