Finding out scroll direction in react-native listv

2019-03-24 14:16发布

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.

2条回答
做个烂人
2楼-- · 2019-03-24 14:53

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;
  };
查看更多
Lonely孤独者°
3楼-- · 2019-03-24 15:06

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);
查看更多
登录 后发表回答