【问题标题】:React Native ScrollView scrollTo spring animationReact Native ScrollView scrollTo 弹簧动画
【发布时间】:2019-04-08 19:30:10
【问题描述】:

我正在使用 React Native 的 ScrollViewscrollTo 方法为滚动视图设置动画。我怎样才能使这个动画加载弹簧,就像Animated.spring 一样(不使用第 3 方库)?

【问题讨论】:

    标签: react-native react-animated react-native-scrollview


    【解决方案1】:

    跟踪滚动位置

    <ScrollView
        ref={(ref) => { this.scrollView = ref; }}
        onScroll={(event) => {
            this.scrollY = event.nativeEvent.contentOffset.y;
        }}
        scrollEventThrottle={16}
    >
    

    然后

    scrollTo(y) {
        if (!this.scrollY) this.scrollY = 0;
        const animatedValue = new Animated.Value(this.scrollY);
        const id = animatedValue.addListener(({ value }) => {
            this.scrollView.scrollTo({ x: 0, y: value, animated: false });
        });
       Animated.spring(animatedValue, { toValue: y }).start(() => { animatedValue.removeListener(id); /* finished callback */ });
    }
    

    【讨论】: