如何让底部标签栏的LottieView在聚焦时仅播放一次Lottie动画
原因说明
当前实现的问题点:
autoPlay属性仅在Lottie组件首次挂载时生效,后续focused状态切换不会触发重新播放- 直接设置
loop={false}后没有手动重置动画进度,会导致动画默认停在结束帧,出现无法播放的假象
解决方案
将Tab图标抽为独立组件,通过Lottie实例引用手动控制动画的重置与播放逻辑,完整实现代码如下:
首先定义通用的Lottie标签图标组件:
import React, { useRef, useEffect } from 'react'; import LottieView from 'lottie-react-native'; const LottieTabIcon = ({ source, focused, size = 24 }) => { const lottieRef = useRef(null); useEffect(() => { if (focused && lottieRef.current) { // 每次聚焦时重置动画到起始帧,再触发播放,保证每次都完整播放一次 lottieRef.current.reset(); lottieRef.current.play(); } }, [focused]); return ( <LottieView ref={lottieRef} source={source} loop={false} autoPlay={false} style={{ width: size, height: size }} /> ); };
修改原有的导航配置,直接使用上述组件:
import React from 'react'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import Home from './Home'; import Create from './Create'; import Messages from './Messages'; import Forum from './Forum'; import Profile from './Profile'; const Tab = createBottomTabNavigator(); export default function Tabs() { return ( <Tab.Navigator screenOptions={({ route }) => ({ tabBarIcon: ({ focused, size }) => { let filePath; switch (route.name) { case 'Home': filePath = require('../tabanimations/hometab.json'); break; case 'Messages': filePath = require('../tabanimations/messagestab.json'); break; case 'Create': filePath = require('../tabanimations/hometab.json'); break; case 'Forum': filePath = require('../tabanimations/forumtab.json'); break; case 'Profile': filePath = require('../tabanimations/profiletab.json'); break; } return <LottieTabIcon source={filePath} focused={focused} size={size} /> }, })}> <Tab.Screen name="Home" component={Home} /> <Tab.Screen name="Messages" component={Messages} /> <Tab.Screen name="Create" component={Create} /> <Tab.Screen name="Forum" component={Forum} /> <Tab.Screen name="Profile" component={Profile} /> </Tab.Navigator> ); }
逻辑说明
- 关闭默认的
autoPlay配置,完全通过实例手动控制播放时机,避免内置逻辑冲突 - 每次标签聚焦时先调用
reset()将动画进度重置到第一帧,再调用play()触发播放,搭配loop={false}即可实现单次播放的效果 - 修复了原代码中
Forum分支缺少break的潜在问题
内容的提问来源于stack exchange,提问作者Ibtsam Ahmad
相关产品推荐
相关产品推荐

