欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > React Native【实战范例】同步跟随滚动

React Native【实战范例】同步跟随滚动

2025/10/20 20:00:39 来源:https://blog.csdn.net/weixin_41192489/article/details/148795183  浏览:    关键词:React Native【实战范例】同步跟随滚动

最终效果

在这里插入图片描述

实现原理

主动滚动区触发滚动事件,原生监听滚动值的变化,并用动画的方式实时同步到跟随滚动区

技术要点

  • 使用 Animated.ScrollView

  • 使用动画变量

    const scrollY = useRef(new Animated.Value(0)).current;
    
  • 主动滚动触发 onScroll,用 Animated.event 实现原生绑定

              onScroll={Animated.event([{nativeEvent: {contentOffset: { y: scrollY },},},],{ useNativeDriver: true })}
    
  • 跟随滚动

    transform: [{ translateY: Animated.multiply(-1, scrollY) }],
    

范例代码

import React, { useRef } from "react";
import { Animated, StyleSheet, View } from "react-native";
const colors = ["red", "green", "blue", "yellow", "orange"];
export default function Demo() {const scrollY = useRef(new Animated.Value(0)).current;const viewList = () => {const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,];return (<>{array.map((item, index) => (<Viewkey={item}style={{width: 60,height: 100,backgroundColor: colors[index % 5],}}/>))}</>);};return (<View style={styles.root}><View style={styles.leftLayout}><Animated.Viewstyle={{width: 60,transform: [{ translateY: Animated.multiply(-1, scrollY) }],}}>{viewList()}</Animated.View></View><View style={styles.rightLayout}><Animated.ScrollViewshowsVerticalScrollIndicator={false}onScroll={Animated.event([{nativeEvent: {contentOffset: { y: scrollY },},},],{ useNativeDriver: true })}>{viewList()}</Animated.ScrollView></View></View>);
}
const styles = StyleSheet.create({root: {width: "100%",height: "100%",flexDirection: "row",justifyContent: "center",},leftLayout: {width: 60,backgroundColor: "#00FF0030",flexDirection: "column",},rightLayout: {width: 60,height: "100%",backgroundColor: "#0000FF30",marginLeft: 100,},
});

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词