Finding out scroll direction in react-native listview/scrollview

自古美人都是妖i 提交于 2019-12-18 03:16:09

问题


Is there a way to find out the scroll direction of react-native's listview/scrollview components?

Native iOS components seem to be able to do it by calculating the offset from scrollViewWillBeginDragging and scrollViewDidScroll, but there seems to be no bindings for these.


回答1:


You can use the onScroll event of a ScrollView and check the contentOffset in the event callback:

https://rnplay.org/apps/FltwOg

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  ScrollView,
  Text,
  View,
} = React;

var SampleApp = React.createClass({
  offset: 0,
  onScroll: function(event) {
    var currentOffset = event.nativeEvent.contentOffset.y;
        var direction = currentOffset > this.offset ? 'down' : 'up';
    this.offset = currentOffset;
    console.log(direction);
  },
  render: function() {
    return (
      <View style={styles.container}>
        <ScrollView style={styles.scroller} onScroll={this.onScroll}>
          <Text>Scrollable content here</Text>
        </ScrollView>
      </View>
    )
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 50,
  },
  scroller: {
    height: 5000,
  },
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);



回答2:


I had problems with alexp's solution to accurately specify the direction when the difference between the old and the new offset was very small. So I filtered them out.

  _onScroll = event => {
    const currentOffset = event.nativeEvent.contentOffset.y;
    const dif = currentOffset - (this.offset || 0);

    if (Math.abs(dif) < 3) {
      console.log('unclear');
    } else if (dif < 0) {
      console.log('up');
    } else {
      console.log('down');
    }

    this.offset = currentOffset;
  };


来源:https://stackoverflow.com/questions/36747541/finding-out-scroll-direction-in-react-native-listview-scrollview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!