寻求Bottom Sheets Navigation与Expo Router兼容方案:旧版本库已失效
当然可以实现两者的兼容,针对新版@gorhom/bottom-sheet(v4+版本),可以按照以下步骤配置:
1. 安装依赖
首先确保安装必要的包:
npx expo install @gorhom/bottom-sheet react-native-gesture-handler react-native-reanimated
同时在babel.config.js中添加Reanimated的Babel插件(必须放在最后):
module.exports = function (api) { api.cache(true); return { presets: ['babel-preset-expo'], plugins: ['react-native-reanimated/plugin'], }; };
2. 创建Bottom Sheet路由布局
在Expo Router的布局文件中(比如app/(tabs)/_layout.tsx),实现嵌套Bottom Sheet的路由容器:
import { Outlet, useRouter } from 'expo-router'; import BottomSheet from '@gorhom/bottom-sheet'; import { View, StyleSheet, useRef } from 'react-native'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; export default function BottomSheetLayout() { const router = useRouter(); const sheetRef = useRef<BottomSheet>(null); // 监听Sheet状态变化,关闭时返回上一页 const handleSheetChange = (index: number) => { if (index === -1) { router.back(); } }; return ( <GestureHandlerRootView style={styles.container}> {/* 主页面内容 */} <Outlet /> {/* 作为导航容器的Bottom Sheet */} <BottomSheet ref={sheetRef} index={1} // 默认展开到第二个锚点 snapPoints={['30%', '80%']} // 定义Sheet的展开高度 onChange={handleSheetChange} enablePanDownToClose > {/* Sheet内的路由内容区域 */} <View style={styles.sheetContent}> <Outlet context={{ sheetRef }} /> </View> </BottomSheet> </GestureHandlerRootView> ); } const styles = StyleSheet.create({ container: { flex: 1, }, sheetContent: { flex: 1, paddingHorizontal: 16, paddingTop: 20, }, });
3. 配置路由结构
在对应目录下创建嵌套路由,比如在app/(tabs)/sheet/下放置需要在Bottom Sheet中展示的页面,Expo Router会自动将这些页面渲染到Sheet内的Outlet中。
关键注意事项
- 必须用
GestureHandlerRootView包裹整个应用的根布局(可放在app/_layout.tsx中),否则手势交互会失效。 - 新版
@gorhom/bottom-sheet的API与旧版本差异较大,比如用index控制展开状态、snapPoints定义锚点高度,旧示例中的属性(如initialSnapIndex)已被移除,需参考官方文档调整。 - 可以通过
useRouter和Sheet的ref,在页面中手动控制Sheet的展开/收起状态。
内容的提问来源于stack exchange,提问作者Michael Falck Wedelgård
相关产品推荐
相关产品推荐

