reactjs - 让变量在 useImperativeHandle 函数中未定义
问题描述
我在 React Native (Expo) 下的 .web.js 文件中使用 lottie-web 包。
我的问题是在 useImperativeHandle 的函数中未定义 let 变量 anim。在 useEffect 动画中效果非常好。例如,如果我在 useEffect 初始化后立即访问 anim.play() ,它就可以工作。但是在命令式的 play() 函数中它不起作用。
在我的父组件中,我使用 useRef 创建一个 ref 并将 ref 传递给组件
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);
},
}));
解决方案
这是因为 React 在 useImperativeHandle 中创建 API 函数时不知道 anim 是什么(闭包和反应更新策略不会通过改变变量来触发任何更新)。有一些方法可以解决这个问题,毕竟,这取决于个人意见该怎么做,我会使用这样最适合我的东西。
添加 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
});
将动画存储在一个状态
将动画存储在仅用于首次渲染的状态中,并在 getApi useEffect 的依赖项数组中使用它
const [anim, setAnim] = React.useState(null);
React.useEffect(() => {
// initialization part
}, []);
React.useImperativeHandle(ref, getAPI(anim), [anim]);
推荐阅读
- java - Java:两个并行列格式
- arduino - Arduino如何检测一个键是否被按下
- c# - Azure 聊天机器人中间件的依赖注入?
- php - Laravel Eloquent orderBy() 一对多关系中的父表字段
- windows - 在 Linux 的 Windows 子系统(Windows 上的 Ubuntu 上的 WSL / Bash)中,如何将颜色重置为默认/原始方案?
- java - 为什么我的地图活动导致我的应用程序崩溃?
- android - 由于只读文件系统,无法在 Android 中打开与 JDBC SQLite 数据库的连接
- spring - @RefreshScope 停止 @Scheduled 任务
- machine-learning - 使您的 SVM 更快、更可靠的最佳方法是什么?
- javascript - 检查 ISO 8601 日期是否早于 5 分钟