如何在 React Native 中集成和使用 Lottie 动画?
在 React Native 中使用 Lottie 动画需要以下步骤:1. 安装依赖npm install lottie-react-native# 或yarn add lottie-react-native对于 iOS,还需要安装 CocoaPods 依赖:cd ios && pod install2. 基本使用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() 或 URLautoPlay:是否自动播放loop:是否循环播放progress:动画进度(0-1)speed:播放速度direction:播放方向(1 正向,-1 反向)colorFilters:颜色过滤器resizeMode:调整模式(cover, contain, center)4. 动画控制方法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. 动态属性修改**jsxconst [animationData, setAnimationData] = useState(null);useEffect(() => { // 动态加载动画 fetch('https://example.com/animation.json') .then(response => response.json()) .then(data => setAnimationData(data));}, []);**6. 事件监听**jsx console.log('Animation finished')} onAnimationLoad={() => console.log('Animation loaded')} onAnimationLoop={() => console.log('Animation looped')}/>**7. 性能优化**- 使用 `useNativeDriver={true}` 启用原生驱动- 对于复杂动画,考虑使用 `LottieView` 的 `cacheComposition` 属性- 在列表中使用时,使用 `FlatList` 的 `removeClippedSubviews` 属性- 避免在不可见的组件中播放动画**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,});// 动态修改颜色```