回到TabRouter中的“上一个标签”

时间:2017-09-01 19:20:35

标签: react-navigation

在react-navigation中,我想使用TabRouter,但在this.props.navigation.goBack()我想要它转到上一个标签。

有没有人知道如何转到上一个标签,我希望它就像设置backBehavior: 'previousTab'一样简单。

我在这里已经破解了解决方案,但由于我不得不修改lib文件,这是一个糟糕的黑客攻击:

我只能通过将backBehavior设置为initialRoute来完成此操作,然后在我的TabRouter上添加自定义getStateForAction,如下所示:

const defaultGetStateForAction = HubNavigator.router.getStateForAction;

HubNavigator.router.getStateForAction = function(action, state) {
    switch (action.type) {
        case NavigationActions.INIT: {
                if (!this.TAB_HISTORY) this.TAB_HISTORY = [];
                this.TAB_HISTORY.length = 0;
                this.TAB_HISTORY.push({ index:ROUTE_INDEX[INITIAL_ROUTE_NAME], params:undefined }); // i dont think INIT ever has params - C:\Users\Mercurius\Pictures\Screenshot -  1, 2017 10.47 AM.png
            break;
        }
        case NavigationActions.NAVIGATE: {
                const { routeName } = action;
                this.TAB_HISTORY.push({ index:ROUTE_INDEX[routeName], params:action.params });
            break;
        }
        case NavigationActions.BACK: {
            if (this.TAB_HISTORY.length === 1) {
                BackHandler.exitApp();
                return null;
            } else {
                const current = this.TAB_HISTORY.pop();
                const previous = this.TAB_HISTORY[this.TAB_HISTORY.length - 1];
                const default_ = defaultGetStateForAction(action, state, ()=>{
                    console.log('returning previous index of:', previous.index);
                    return previous.index
                });
                default_.index = previous.index;
                default_.routes[previous.index].params = previous.params;
                return default_;
            }
        }
    }

    return defaultGetStateForAction(action, state);
}

我所做的是,在NavigationActions.BACK上我修改了返回的对象索引,使其具有我在数组this.TAB_HISTORY中保存的上一个索引。

然而,当我启动应用程序时,从初始选项卡切换到选项卡2,然后从选项卡2切换回初始选项卡...按“返回”将不执行任何操作,因为activeTabIndex始终设置为initialRouteIndex - https://github.com/react-community/react-navigation/blob/5e075e1c31d5e6192f2532a815b1737fa27ed65b/src/routers/TabRouter.js#L138

所以你在我上面的修复中看到我将第三个参数传递给defaultGetStateForAction并返回索引,但我必须为此修改react-navigation/src/routers/TabRouter.js,这不是我想要做的。

有没有人知道如何转到上一个标签,我希望它就像设置backBehavior: 'previousTab'一样简单。

以下是我的HubNavigator,以防你想看到:

const ROUTE_INDEX = { Players: 0, Girls: 1, Customers: 2, Assets: 3 };
const INITIAL_ROUTE_NAME = 'Players';
const HubNavigator = TabNavigator(
    {
        Players:   { screen:ScreenPlayers },
        Girls:     { screen:ScreenGirls },
        Customers: { screen:ScreenCustomers },
        Assets:    { screen:ScreenAssets }
    },
    {
        initialRouteName: INITIAL_ROUTE_NAME,
        backBehavior: 'initialRoute',
        cardStyle: styles.card,
        order: Object.entries(ROUTE_INDEX).sort(([,indexA], [,indexB]) => indexA - indexB).map(([routeName]) => routeName),
    }
)

0 个答案:

没有答案