如何在react-native-bottom-sheet中用animatedPosition追踪面板y轴位置?
解决BottomSheet实时位置追踪问题
要实时获取BottomSheet沿Y轴移动的每一个像素值,你需要调整useDerivedValue的使用方式,并修正代码里的几个问题:
- Reanimated的
useDerivedValue运行在工作线程,不能直接调用主线程的console.log,必须用runOnJS包裹 - 确保正确导入依赖(比如
PROVIDER_GOOGLE) - 确认BottomSheet库的导入路径正确(gorhom的官方库是
@gorhom/bottom-sheet)
修正后的完整代码:
import BottomSheet from '@gorhom/bottom-sheet'; import React, { useEffect, useState } from 'react'; import { StyleSheet, View, LogBox } from 'react-native'; import { useSharedValue, useDerivedValue, runOnJS } from 'react-native-reanimated'; import MapView, { PROVIDER_GOOGLE } from 'react-native-maps'; // 忽略不必要的嵌套警告 LogBox.ignoreLogs(['VirtualizedLists should never be nested']); export default function App() { const animatedPosition = useSharedValue(0); const snapPoints = [100, 200, 500]; const [currentPosition, setCurrentPosition] = useState(0); // 定义主线程的日志函数 const logPosition = (value) => { console.log('实时Y轴位置:', value); }; // 监听animatedPosition的实时变化 useDerivedValue(() => { // 调用主线程的日志函数 runOnJS(logPosition)(animatedPosition.value); }, [animatedPosition]); useEffect(() => { console.log('当前切换的锚点索引:', currentPosition); }, [currentPosition]); return ( <View style={styles.container}> <MapView style={styles.map} provider={PROVIDER_GOOGLE} /> <BottomSheet snapPoints={snapPoints} animatedPosition={animatedPosition} onChange={(index) => setCurrentPosition(index)} index={0} > <View style={{ width: '100%', height: '100%', backgroundColor: 'green', }} /> </BottomSheet> </View> ); }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject }, map: { ...StyleSheet.absoluteFillObject }, });
关键说明:
runOnJS的使用:将日志操作包装在runOnJS中,确保代码在JS主线程执行,这样才能正常打印实时位置值。- 库导入修正:把
reanimated-bottom-sheet改为@gorhom/bottom-sheet,匹配官方库版本。 - 依赖补全:导入
PROVIDER_GOOGLE并忽略BottomSheet常见的嵌套警告,避免控制台干扰。
这样修改后,你就能在控制台看到BottomSheet移动过程中每一个时刻的Y轴像素值,同时onChange可以继续监听锚点切换的索引。
内容的提问来源于stack exchange,提问作者MouseWarrior
相关产品推荐
相关产品推荐

