如何调用react-native-curved-bottom-bar的setVisible API?
如何调用react-native-curved-bottom-bar的setVisible方法隐藏底部菜单
要调用setVisible(boolean)方法控制底部栏的显示/隐藏,核心是先获取组件的引用(ref),再通过ref调用方法,具体步骤如下:
1. 创建并绑定CurvedBottomBar的ref
不管是函数组件还是类组件,都需要先创建一个ref,绑定到CurvedBottomBar组件上:
函数组件(使用useRef)
import React, { useRef } from 'react'; import { TouchableOpacity, Text } from 'react-native'; import { CurvedBottomBar } from 'react-native-curved-bottom-bar'; const HomeScreen = () => { // 创建ref const bottomBarRef = useRef(null); // 隐藏底部栏 const hideBottomNav = () => { bottomBarRef.current?.setVisible(false); }; // 显示底部栏 const showBottomNav = () => { bottomBarRef.current?.setVisible(true); }; return ( <> {/* 示例触发按钮 */} <TouchableOpacity onPress={hideBottomNav} style={{ padding: 16 }}> <Text>隐藏底部菜单</Text> </TouchableOpacity> <TouchableOpacity onPress={showBottomNav} style={{ padding: 16 }}> <Text>显示底部菜单</Text> </TouchableOpacity> {/* 绑定ref到CurvedBottomBar */} <CurvedBottomBar ref={bottomBarRef} initialRouteName="Home" tabBar={({ routeName, selectedTab, navigate }) => ( // 你的tabBar内容配置,比如底部按钮 )} // 其他必要props /> </> ); }; export default HomeScreen;
类组件(使用createRef)
import React, { Component, createRef } from 'react'; import { TouchableOpacity, Text } from 'react-native'; import { CurvedBottomBar } from 'react-native-curved-bottom-bar'; class HomeScreen extends Component { constructor(props) { super(props); this.bottomBarRef = createRef(); } hideBottomNav = () => { this.bottomBarRef.current?.setVisible(false); }; showBottomNav = () => { this.bottomBarRef.current?.setVisible(true); }; render() { return ( <> <TouchableOpacity onPress={this.hideBottomNav} style={{ padding: 16 }}> <Text>隐藏底部菜单</Text> </TouchableOpacity> <TouchableOpacity onPress={this.showBottomNav} style={{ padding: 16 }}> <Text>显示底部菜单</Text> </TouchableOpacity> <CurvedBottomBar ref={this.bottomBarRef} initialRouteName="Home" tabBar={({ routeName, selectedTab, navigate }) => ( // 你的tabBar内容配置 )} // 其他必要props /> </> ); } } export default HomeScreen;
2. 调用时机
你可以在任何需要的逻辑中调用setVisible:
- 按钮点击事件(如示例)
- 页面滚动到特定位置时(比如ScrollView的onScroll回调)
- 组件状态变化时(比如某个弹窗显示/隐藏时)
注意事项
- 确保ref正确绑定到
CurvedBottomBar组件,否则bottomBarRef.current会是null,调用方法会无效果 - 使用可选链操作符
?.可以避免current为null时的报错
内容的提问来源于stack exchange,提问作者Marek Tandler
相关产品推荐
相关产品推荐

