React Native:实现自定义底部导航栏当前页面图标激活状态
实现React Native自定义底部导航栏的激活状态切换
我来帮你搞定这个底部导航栏的激活状态显示功能!核心思路就是用状态管理当前选中的页面索引,然后根据索引来切换对应图标的普通/激活版本,同时可以同步调整文字样式强化选中效果。
下面是修改后的完整代码,关键部分我都加了注释:
import React, { useState } from 'react'; import { Dimensions, View, Image, TouchableOpacity, Text, Platform } from 'react-native'; const { width, height } = Dimensions.get("window"); import images from '../path/to/your/images'; // 替换成你实际的图片路径 // 定义导航栏的所有项,把普通图标、激活图标、页面名称、对应页面组件统一管理 const navItems = [ { id: 'home', title: '首页', normalIcon: images.home, // 普通状态图标,比如home.png activeIcon: images.homeActive, // 激活状态图标,比如home-active.png screenComponent: () => <View><Text>首页内容</Text></View> // 替换成你的实际页面组件 }, { id: 'profile', title: '我的', normalIcon: images.profile, activeIcon: images.profileActive, screenComponent: () => <View><Text>个人中心</Text></View> }, // 可以继续添加更多导航项 ]; const CustomBottomNav = () => { // 状态:跟踪当前选中的导航项索引,默认选中第一个 const [currentActiveIndex, setCurrentActiveIndex] = useState(0); return ( <View> {/* 页面内容区域:渲染当前选中的页面 */} <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> {navItems[currentActiveIndex].screenComponent()} </View> {/* 底部导航栏 */} <View style={{ flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', height: Platform.OS === 'ios' ? 80 : 60, width: width, backgroundColor: '#fff', borderTopWidth: 1, borderTopColor: '#eee', paddingBottom: Platform.OS === 'ios' ? 20 : 0 }} > {navItems.map((item, index) => ( <TouchableOpacity key={item.id} onPress={() => setCurrentActiveIndex(index)} // 点击切换当前选中索引 style={{ justifyContent: 'center', alignItems: 'center' }} > {/* 根据当前索引判断显示普通图标还是激活图标 */} <Image source={currentActiveIndex === index ? item.activeIcon : item.normalIcon} style={{ width: 24, height: 24, marginBottom: 4 }} resizeMode="contain" /> {/* 文本样式随激活状态变化 */} <Text style={{ fontSize: 12, color: currentActiveIndex === index ? '#1677ff' : '#666' }} > {item.title} </Text> </TouchableOpacity> ))} </View> </View> ); }; export default CustomBottomNav;
关键逻辑说明:
- 状态管理:用
useState创建currentActiveIndex,记录当前选中的导航项位置,点击时更新这个状态。 - 统一配置导航项:把所有导航相关的信息放到
navItems数组里,后续新增或修改导航项只需要修改这个数组,维护起来更方便。 - 图标与样式切换:通过
currentActiveIndex === index这个条件判断,决定渲染普通图标还是激活图标,同时调整文字颜色来强化选中状态。 - 页面切换:直接渲染当前选中项对应的
screenComponent,如果你的项目用了React Navigation,也可以把onPress里的逻辑改成navigation.navigate(item.id),配合路由来实现页面跳转。
你只需要把代码里的图片路径、页面组件替换成你自己的实际内容,就能实现想要的激活状态显示效果啦!
内容的提问来源于stack exchange,提问作者FortuneCookie
相关产品推荐
相关产品推荐

