在React Native的TabNavigator中再次按下时滚动到当前选项卡的顶部

时间:2020-01-02 09:29:52

标签: javascript react-native react-native-flatlist

我对本地应用程序有BottomTabNavigator的反应。在这种情况下,如果所选的当前标签页已向下滚动FlatList,然后在导航器中按下下一个标签页,然后再次导航回上一个标签页,则滚动条仍位于该位置,即向下。导航后如何滚动到当前选项卡的顶部?

我拥有的是:

navigation.js

 import {createBottomTabNavigator} from "react-navigation";
     .....................................

    name: {
    screen: createBottomTabNavigator({
      first: { screen: firstNavigation },
      second: { screen: secondNavigation },
      third: { screen: thirdNavigation }
    })
  } 

我在底部有三个选项卡,分别名为first,second和Third,从第一个导航到第二个,第二个选项卡的faltlist出现了此问题。

second.js

        <View>
          <FlatList
            data={this.causes}
            keyExtractor={this._keyExtractor}
            renderItem={this._onPress}
            contentContainerStyle={styles.flatListContainer}
          />
        </View>

1 个答案:

答案 0 :(得分:3)

一种解决方案是跟踪聚焦屏幕, 像this

 componentDidMount() {
    const { navigation } = this.props;
    this.focusListener = navigation.addListener('didFocus', () => {
      // The screen is focused
      // Call any action
    });
  }

  componentWillUnmount() {
    // Remove the event listener
    this.focusListener.remove();
  }

您需要添加参考到您的单位列表:

 <FlatList
        ref={(ref) => { this._flatList = ref; }}
        data={this.causes}
        keyExtractor={this._keyExtractor}
        renderItem={this._onPress}
        contentContainerStyle={styles.flatListContainer}
      />

只要焦点屏幕是带有平面列表的屏幕,就可以使用 scrollToIndex方法:

this._flatList.scrollToIndex({animated: true, index: 0});
相关问题