hooks 与 animejs
animejs 是现如今非常不错的一个 js 动画库。我们将其与 react Hooks 融合,使它更方便的在 react 中使用。
最终效果:
const Animate: React.FC = () => {
const { animateTargetRef, animationRef } = useAnime({
translateX: 300,
loop: true,
duration: 2000,
autoplay: false,
});
useEffect(() => {
setTimeout(() => {
animationRef.current?.play?.();
}, 3000);
}, [animationRef]);
return (
<div
ref={animateTargetRef}
style={{ width: '100px', height: '100px', backgroundColor: 'black' }}
/>
);
};
首先看看 animejs 在一般的 JS 和 html 中如何使用:
<div class="xxx"></div>
import anime from 'animejs';
const animation = anime({
translateX: 300,
loop: true,
duration: 2000,
autoplay: false,
targets: '.xxx',
});
animation.play();
但是在 React 中,我们不想要到处写这些玩意儿。我们喜欢 hooks!
所以我们可以封装一个 useAnime hook。
第一步,我们可以引入 AnimeParams,让我们的 hook 拥有代码提示:
import anime, { AnimeParams } from 'animejs';
export const useAnime = (props: AnimeParams) => {
anime(props);
};
然后我们通过 useRef 将 anime 的 targets 绑定,并且暴露出去,供其他地方使用。
//...
const animateTargetRef = useRef<any>(null);
useLayoutEffect(() => {
if (!animationTargetRef.current) {
console.warn('please bind animation target ref');
return;
}
animate({
...props,
targets: [animationTargetRef.current],
});
}, [props]);
return { animateTargetRef };
//...
通过观察发现,animate 返回的是 AnimeInstance 类型,我们从 animejs 中导入:
import anime, { AnimeParams, AnimeInstance } from 'animejs';
// ...
const animationRef = useRef<AnimeInstance>();
// ...
animationRef.current = animate({
...props,
targets: [animationTargetRef.current],
});
// ...
return { animateTargetRef, animationRef };
这样就轻松完成了 useAnime 的封装。
https://www.houdianzi.com/ logo设计公司
完整代码:
import anime, { AnimeParams, AnimeInstance } from 'animejs';
import { useRef, useLayoutEffect } from 'react';
export const useAnime = (props: AnimeParams = {}) => {
const animateTargetRef = useRef<any>();
const animationRef = useRef<AnimeInstance>();
useLayoutEffect(() => {
if (!animateTargetRef.current) {
console.warn('please bind the anime ref while useAnime');
return;
}
animationRef.current = anime({
...props,
targets: [animateTargetRef.current],
});
}, [props]);
return { animateTargetRef, animationRef };
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架