ScrollView React Native 中的回调scrollTo

Fan*_*sim 4 react-native

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

scrollTo({y: 0, animated: true})
Run Code Online (Sandbox Code Playgroud)

但默认情况下该函数没有第二个参数。

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

And*_*sky 6

onMomentumScrollEnd您可以按照本期所述使用

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

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,
  },
});
Run Code Online (Sandbox Code Playgroud)