You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让底部标签栏的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:39:04