You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

关键说明:

  1. runOnJS的使用:将日志操作包装在runOnJS中,确保代码在JS主线程执行,这样才能正常打印实时位置值。
  2. 库导入修正:把reanimated-bottom-sheet改为@gorhom/bottom-sheet,匹配官方库版本。
  3. 依赖补全:导入PROVIDER_GOOGLE并忽略BottomSheet常见的嵌套警告,避免控制台干扰。

这样修改后,你就能在控制台看到BottomSheet移动过程中每一个时刻的Y轴像素值,同时onChange可以继续监听锚点切换的索引。

内容的提问来源于stack exchange,提问作者MouseWarrior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:25:15