React Native GestureHandler中调用Lottie动画报错:null不是对象
问题原因及解决方案
核心原因
useAnimatedGestureHandler的回调函数(比如onStart、onActive)运行在UI线程的Worklet环境中,和React的JS主线程完全隔离。你用useRef创建的Lottie引用属于主线程JS环境,Worklet代码无法直接访问这个引用,所以会出现lottie.current为null的错误。
而useEffect的回调在JS主线程执行,自然能正常获取useRef的引用并调用play方法。
解决方法
要在手势回调中调用Lottie的play方法,必须把调用逻辑切回JS主线程执行,这可以通过Reanimated提供的runOnJS函数实现:
- 在主线程定义一个调用Lottie播放的函数
- 在手势回调中用
runOnJS包裹这个函数,触发主线程执行
代码示例
import React, { useRef, useEffect } from 'react'; import { View } from 'react-native'; import LottieView from 'lottie-react-native'; import { GestureDetector, Gesture } from 'react-native-gesture-handler'; import { useAnimatedGestureHandler, runOnJS } from 'react-native-reanimated'; const LottieGestureComponent = () => { const lottie = useRef(null); // 主线程执行的播放函数 const playLottieSegment = () => { lottie.current?.play(0, 15); }; const tapGestureHandler = useAnimatedGestureHandler({ onStart: () => { // 将播放逻辑调度回主线程 runOnJS(playLottieSegment)(); }, }); const tapGesture = Gesture.Tap().onGestureEvent(tapGestureHandler); // 验证:useEffect中正常执行 useEffect(() => { playLottieSegment(); }, []); return ( <GestureDetector gesture={tapGesture}> <View style={{ width: 200, height: 200 }}> <LottieView ref={lottie} source={require('./your-animation.json')} loop={false} autoPlay={false} /> </View> </GestureDetector> ); }; export default LottieGestureComponent;
关键说明
runOnJS的作用是把传入的函数调度到JS主线程执行,这样就能访问到主线程中useRef保存的Lottie实例了。- 使用可选链操作符
?.可以避免在lottie.current为null时抛出错误,增加代码健壮性。
内容的提问来源于stack exchange,提问作者Benjamin Jones
相关产品推荐
相关产品推荐

