乐闻世界logo
搜索文章和话题

如何在 React Native 中集成和使用 Lottie 动画?

2月19日 17:55

在 React Native 中使用 Lottie 动画需要以下步骤:

1. 安装依赖

bash
npm install lottie-react-native # 或 yarn add lottie-react-native

对于 iOS,还需要安装 CocoaPods 依赖:

bash
cd ios && pod install

2. 基本使用

jsx
import LottieView from 'lottie-react-native'; import { useRef, useEffect } from 'react'; const MyComponent = () => { const animationRef = useRef(null); useEffect(() => { // 自动播放动画 animationRef.current?.play(); }, []); return ( <LottieView ref={animationRef} source={require('./animation.json')} autoPlay={false} loop={true} style={{ width: 200, height: 200 }} /> ); };

3. 常用属性

  • source:动画数据源,可以是 require() 或 URL
  • autoPlay:是否自动播放
  • loop:是否循环播放
  • progress:动画进度(0-1)
  • speed:播放速度
  • direction:播放方向(1 正向,-1 反向)
  • colorFilters:颜色过滤器
  • resizeMode:调整模式(cover, contain, center)

4. 动画控制方法

jsx
const animationRef = useRef(null); // 播放动画 animationRef.current?.play(); // 暂停动画 animationRef.current?.pause(); // 停止动画并重置 animationRef.current?.reset(); // 播放到指定进度 animationRef.current?.play(30, 60); // 从 30% 播放到 60% // 设置进度 animationRef.current?.setProgress(0.5); // 设置到 50% **5. 动态属性修改** ```jsx const [animationData, setAnimationData] = useState(null); useEffect(() => { // 动态加载动画 fetch('https://example.com/animation.json') .then(response => response.json()) .then(data => setAnimationData(data)); }, []); <LottieView source={animationData} autoPlay loop />

6. 事件监听

jsx
<LottieView source={require('./animation.json')} onAnimationFinish={() => console.log('Animation finished')} onAnimationLoad={() => console.log('Animation loaded')} onAnimationLoop={() => console.log('Animation looped')} />

7. 性能优化

  • 使用 useNativeDriver={true} 启用原生驱动
  • 对于复杂动画,考虑使用 LottieViewcacheComposition 属性
  • 在列表中使用时,使用 FlatListremoveClippedSubviews 属性
  • 避免在不可见的组件中播放动画

8. 常见问题解决

  • 动画不显示:检查 JSON 文件路径是否正确
  • 动画卡顿:检查设备性能,考虑降低帧率
  • iOS 上不工作:确保已运行 pod install
  • Android 上不工作:检查 Gradle 配置

9. 高级用法

jsx
// 使用 LottieComposition 预加载动画 import { useLottie } from 'lottie-react-native'; const { View } = useLottie({ src: require('./animation.json'), loop: true, autoPlay: true, }); // 动态修改颜色 <LottieView source={require('./animation.json')} colorFilters={[ { keypath: 'layer1', color: '#FF0000' } ]} />
标签:React NativeLottie