React Navigation: Scroll to top if tab is the same

2019-04-15 05:14发布

I have a tab-based app. If I'm currently on the first tab, scrolled all the way down, and I click the tab again, I want it to scroll to the top. Is this possible?

I know I should have a scroll view with a reference and then use this._scrollView.scrollTo(0), but how can I detect when the user taps the tabbar and decide whether it is the same tab?

2条回答
等我变得足够好
2楼-- · 2019-04-15 05:27

tabBarOnPress in navigationOptions. Callback to handle tap events; the argument is an object containing:

the previousScene: { route, index }: the scene which we are leaving. the scene: { route, index } that was tapped. the jumpToIndex method that can perform the navigation for you.

so in your case just use scene object to check which tab is pressed.

check more on react navigation documentation.

查看更多
Summer. ? 凉城
3楼-- · 2019-04-15 05:38

You can create your tab navigator as follow:

const TabNav = TabNavigator({
   // config
},
{
   navigationOptions: ({ navigation }) => ({
        tabBarOnPress: (scene, jumpToIndex) => {
            // Called when tab is press
        },
    }),
});

In order to scroll to top, you can check this solution:

  1. https://github.com/react-navigation/react-navigation/issues/2955#issuecomment-343422076
  2. https://snack.expo.io/HJp9mEQkG
查看更多
登录 后发表回答