如何在React Native中用Gorhom BottomSheet实现随底部Sheet联动的悬浮按钮
构建随Gorhom BottomSheet联动的悬浮按钮(仿Lyft UI)
核心思路
利用Gorhom BottomSheet暴露的animatedPosition动画值,通过React Native Reanimated计算悬浮按钮的位移,实现按钮与Sheet的同步上下移动。
实现步骤
确认依赖安装
先确保已安装所需依赖:npm install @gorhom/bottom-sheet react-native-reanimated react-native-gesture-handler注意:React Native Reanimated需要额外配置babel插件,按照官方文档完成基础配置即可。
核心代码实现
下面是完整示例,关键是通过bottomSheetRef获取Sheet的实时位置,映射到悬浮按钮的位移:import React, { useRef } from 'react'; import { View, TouchableOpacity, StyleSheet } from 'react-native'; import BottomSheet from '@gorhom/bottom-sheet'; import Animated, { useAnimatedStyle, interpolate, Extrapolate } from 'react-native-reanimated'; const FloatingButtonSheet = () => { const bottomSheetRef = useRef<BottomSheet>(null); // 定义Sheet停靠高度,按需调整 const snapPoints = [120, 350, 650]; // 计算悬浮按钮的动画样式 const floatingButtonStyle = useAnimatedStyle(() => { const sheetPos = bottomSheetRef.current?.animatedPosition.value ?? 0; // 映射Sheet位置到按钮位移:Sheet上移时按钮同步跟随 const translateY = interpolate( sheetPos, [0, snapPoints[1], snapPoints[2]], [0, -230, -530], Extrapolate.CLAMP ); return { transform: [{ translateY }] }; }); return ( <View style={styles.container}> {/* 悬浮按钮 */} <Animated.View style={[styles.btnWrapper, floatingButtonStyle]}> <TouchableOpacity style={styles.floatingBtn}> {/* 这里放入图标/文字,比如Lyft的加号图标 */} </TouchableOpacity> </Animated.View> {/* Gorhom BottomSheet */} <BottomSheet ref={bottomSheetRef} snapPoints={snapPoints} index={1} // 默认停靠在中间高度 style={styles.sheet} > <View style={styles.sheetContent}> {/* Sheet内部UI内容 */} </View> </BottomSheet> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f5f5f5', }, btnWrapper: { position: 'absolute', bottom: 90, // 初始位置对应Sheet默认停靠高度 alignSelf: 'center', zIndex: 10, }, floatingBtn: { width: 64, height: 64, borderRadius: 32, backgroundColor: '#ff00bf', justifyContent: 'center', alignItems: 'center', shadowColor: '#000', shadowOffset: { width: 0, height: 3 }, shadowOpacity: 0.3, shadowRadius: 5, elevation: 6, }, sheet: { backgroundColor: '#fff', }, sheetContent: { flex: 1, paddingHorizontal: 20, }, }); export default FloatingButtonSheet;细节调整
- 修改
interpolate的映射值:根据你的snapPoints和按钮初始位置,调整位移数组的数值,保证按钮与Sheet移动节奏匹配。 - 若需要额外动画效果,可在
useAnimatedStyle中添加scale或opacity属性。 - 确保按钮
zIndex高于Sheet,避免被遮挡。
- 修改
注意事项
- 必须正确配置React Native Reanimated,否则动画无法正常触发。
- 若Sheet有自定义头部或手柄,需调整按钮初始位置和位移值适配布局。
内容的提问来源于stack exchange,提问作者Macy Yash
相关产品推荐
相关产品推荐

