hooks 與 animejs
本文寫于 2020 年 1 月 13 日
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 ></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 的封裝,
完整代碼:
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 };
};
(完)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/248480.html
標籤:其他
