reactjs - useImperativeHandle 函数中 let 变量未定义

标签 reactjs react-native lottie react-native-web

我在 React Native (Expo) 下使用 .web.js 文件中的lottie-web 包。

我的问题是 let 变量 anim 在 useImperativeHandle 的函数中未定义。在 useEffect 中动画效果非常好。例如,如果我在 useEffect 初始化后立即访问 anim.play() ,它就会起作用。但在命令式的 play() 函数中它不起作用。

在我的父组件中,我使用 useRef 创建一个引用并将该引用传递给组件

const lottieAnim = useRef(null);

--

let anim;
useEffect(() => {
  const lottieOptions = {
    container: divContainer.current,
    renderer: 'svg',
    loop,
    autoplay,
    segments: segments !== false,
    animationData,
    rendererSettings,
  };
  anim = lottie.loadAnimation({ ...lottieOptions, ...options });
  // anim.play(); works here 

  if (onAnimationFinish) {
    anim.addEventListener('complete', onAnimationFinish);
  }
}, []);

useImperativeHandle(ref, () => ({
  stop() {
    anim.stop();
  },
  pause() {
    anim.pause();
  },
  play() {
    anim.play();
    // anim is undefined
  },
  setSpeed(s) {
    anim.setSpeed(s);
  },
  setDirection(d) {
    anim.setDirection(d);
  },
  playSegments(s) {
    anim.playSegments(s);
  },
}));

最佳答案

2023 年更新

我创建了一个包,用于连接第三方包,以更简单的方式通过 useImperativeHandler 使用react,您可能会发现它有用且更易于使用😊。
react-aptor

这是因为 React 在 useImperativeHandle 中创建 API 函数时不知道 anim 是什么(由于闭包和 React 更新策略不会通过改变变量来触发任何更新)。有一些方法可以解决这个问题,毕竟,这取决于个人意见,我会使用这样的方法,效果最好 对我来说。

添加GetApi函数

// hanlder.js
const stop = anim => anim.stop()
// api.js
const getAPI = anim => () => ({
  stop: stop.bind(this, anim),
  // or simply
  setSpeed: s => anim.setSpeed(s),

  // you can mock APIs here if anim is null or throw an Error
});

anim 存储在某种状态

store anim in the state for the first render only and use it in the dependencies array of getApi useEffect

const [anim, setAnim] = React.useState(null);

React.useEffect(() => {
  // initialization part
}, []);

React.useImperativeHandle(ref, getAPI(anim), [anim]);

关于reactjs - useImperativeHandle 函数中 let 变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65900451/

相关文章:

reactjs - 将 Flow.js 与 React 复合组件结合使用

javascript - 您正在导入一个需要 useState 的组件。它仅在客户端组件中有效,但其父组件均未标记为 "use client"

react-native - Expo sound,如何获得声音的持续时间

react-native - 世博会 + 排毒 + CircleCI

javascript - react : Flow: Import a local js file - cannot resolve issue module

java - Lottie - setProgress 无法正常工作

reactjs - 忽略并跳过 requirejs 依赖

javascript - Jest 一次性模拟多个组件

java - 使用 Graphics2D 绘制 TYPE_INT_ARGB_PRE 类型的 BufferedImage 时遇到问题

android - Lottie.Forms 中不存在类型或命名空间 'Droid'