当前位置: 首页 > news >正文

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,},
});

相关文章:

  • 【音视频】RTMP协议详解
  • 云计算与5G:如何利用5G网络优化云平台的性能
  • Github 2025-06-20 Java开源项目日报Top8
  • 一体三面:UEBA在数据分析、数据治理与数据安全中的应用洞察
  • 前端开发面试题总结-vue3框架篇
  • 视觉分析在摄像头偏移检测中的应用
  • 汽车前纵梁焊接总成与冲压件的高效自动化三维检测方案
  • 机器学习流量识别(pytorch+NSL-KDD+多分类建模)
  • I排序算法.go
  • DAY 37 早停策略和模型权重的保存
  • el-table复选框分页多选
  • 论文阅读笔记:Digging Into Self-Supervised Monocular Depth Estimation
  • 20250620在Ubuntu20.04.6下编译KickPi的K7的Android14系统
  • 求助帖:学Java开发方向还是网络安全方向前景好
  • 解锁决策树:数据挖掘的智慧引擎
  • iOS应用启动时间优化:通过多工具协作提升iOS App性能表现
  • 展锐android13修改开机logo和开机图片
  • 高效打印 PDF 文档:基础操作与自动打印(含C# .NET方案)
  • 信安实验室CTF writeup
  • 通过事件过滤器拦截QRadioButton点击事件
  • 东莞网站推广案例/百度搜索关键词排行榜
  • 备案关闭网站/线上营销渠道
  • 天迈装饰网站建设项目/上海百度seo公司
  • 新公司董事长致辞做网站/东莞有限公司seo
  • 做网站为什么能赚钱吗/优化大师app
  • 网络营销怎么做网站/网站创建免费用户