我有一个钩子,用于抽象requestAnimationFrame
:
export const useAnimationIncrease = ({
easingName = EasingName.linear,
diff: end,
duration = 500
}: AnimationIncreaseProps) => {
const [increase, setIncrease] = useState(0);
const start = useRef<any>(null);
useLayoutEffect(() => {
let raf: number;
const frame = (timestamp: number) => {
if (!start.current) {
start.current = timestamp;
}
const time = timestamp - start.current;
// get percent of completion in range [0, 1]
const percentRange = Math.min(time / duration, 1);
const percent = easing[easingName as string](percentRange);
setIncrease(increase + end * percent);
if (time < duration) {
raf = requestAnimationFrame(frame);
}
};
raf = requestAnimationFrame(frame);
return () => {
cancelAnimationFrame(raf);
};
}, [end]);
return increase;
};
这是它的使用方法:
const increase = useAnimationIncrease({ easingName: EasingName.inOutCubic, diff: 10 });
它将每次返回增量,因此我可以将其用于滚动等操作。
但如果我想在按钮点击时触发它,该怎么办?或者我的方法不正确吗?
如果我尝试这样做:
onClick={(e) => {
const increase = useAnimationIncrease({ easingName: EasingName.inOutCubic, diff: 10 });
// use increase
}
然后我收到了错误信息:
钩子函数只能在函数组件的主体内调用。
onClick
处理程序是否在类组件内?您的react
和react-dom
版本是什么? - maazadeeb