回调scrollTo在ScrollView React Native中

时间:2017-10-17 08:59:09

标签: react-native

我想在函数scrollTo的末尾调用一个函数,如下所示:

scrollTo({y: 0, animated: true})

但默认情况下,此功能没有第二个参数。

那么如何处理滚动动画的结束以触发其他功能呢?

1 个答案:

答案 0 :(得分:1)

您可以使用this issue

中提到的onMomentumScrollEnd

但是,如果您想要更好地控制滚动状态,可以像这样实现smth



import React from 'react';
import { StyleSheet, Text, View, ScrollView, Button } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <ScrollView 
          style={{ marginVertical: 100 }} 
          ref={this.refScrollView}
          onScroll={this.onScroll}
        >
          <Text style={{ fontSize: 20 }}>
            A lot of text here...
          </Text>
        </ScrollView>

        <Button title="Scroll Text" onPress={this.scroll} />
      </View>
    );
  }

  componentDidMount() {
    this.scrollY = 0;
  }

  onScroll = ({ nativeEvent }) => {
    const { contentOffset } = nativeEvent;
    this.scrollY = contentOffset.y;
    
    if (contentOffset.y === this.onScrollEndCallbackTargetOffset) {
      this.onScrollEnd()
    }
  }

  onScrollEnd = () => {
    alert('Text was scrolled')
  }

  refScrollView = (scrollView) => {
    this.scrollView = scrollView;
  }

  scroll = () => {
    const newScrollY = this.scrollY + 100;
    this.scrollView.scrollTo({ y: newScrollY, animated: true });
    this.onScrollEndCallbackTargetOffset = newScrollY;
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 20,
  },
});
&#13;
&#13;
&#13;