首页 > 解决方案 > 如何在 Typescript 中将 ref prop 和 useRef 与 Lottie 文件一起使用?

问题描述

编辑:我意识到这实际上正在工作,尽管有错误消息!所以我真的不需要实施帮助,但想知道如何摆脱错误。为什么即使代码正在运行,它也会给我一个错误,我应该改变什么来摆脱它(除非我应该忽略它,因为代码正在运行?)?当我正在学习 Typescript 以获得有关解释此类错误的解释时,这将非常有帮助。

我正在将 Typescript 与 React Native 一起使用,并且我希望只能播放到我的 lottie 文件的某个帧。这是我尝试过的:

const lottieRef = useRef<LottieView>();

useEffect(() => {
    if (lottieRef && lottieRef.current) {
      lottieRef.current.play(0, 120);
    }
  });

  return (
    <LottieView
      ref={lottieRef}
      source={SUCCESS.keepReading}
      autoPlay
      loop={false}
      style={styles.animationContainer}
    />
  );

并且 ref 带有这条长错误消息的下划线:

No overload matches this call.
  Overload 1 of 2, '(props: AnimatedLottieViewProps | Readonly<AnimatedLottieViewProps>): AnimatedLottieView', gave the following error.
    Type 'MutableRefObject<AnimatedLottieView | undefined>' is not assignable to type 'LegacyRef<AnimatedLottieView> | undefined'.
      Type 'MutableRefObject<AnimatedLottieView | undefined>' is not assignable to type 'RefObject<AnimatedLottieView>'.
        Types of property 'current' are incompatible.
          Type 'AnimatedLottieView | undefined' is not assignable to type 'AnimatedLottieView | null'.
            Type 'undefined' is not assignable to type 'AnimatedLottieView | null'.
  Overload 2 of 2, '(props: AnimatedLottieViewProps, context: any): AnimatedLottieView', gave the following error.
    Type 'MutableRefObject<AnimatedLottieView | undefined>' is not assignable to type 'LegacyRef<AnimatedLottieView> | undefined'.ts(2769)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<AnimatedLottieView> & Readonly<AnimatedLottieViewProps> & Readonly<...>'
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<AnimatedLottieView> & Readonly<AnimatedLottieViewProps> & Readonly<...>'

我是 typescript 和 lottie 文件的新手,所以如果这是一个明显的问题,我很抱歉!提前非常感谢!

标签: reactjstypescriptreact-nativelottieuse-ref

解决方案


不得不改为

const lottieRef = useRef<LottieView>(null);

并修复了它!


推荐阅读