【发布时间】:2021-06-27 07:46:24
【问题描述】:
我有一个函数,它使用 CSS 动画动态更改页面上的对象。
我从 onclick 和 touchend 事件中调用此函数。
如果动画仍在进行中,我想阻止此函数运行/调用。
奇怪的是,在下面的代码中,即使来自 console.log(isLoading) 的 isLoading 等于 false,也会调用函数 changeItem。
const [isLoading, setIsLoading] = useState(false);
const changeItemHandler = (mod, index) => {
console.log(isLoading);
if (isLoading === true) return;
else {
setIsLoading(true);
changeItem(mod, index); //at the end of animation setIsLoading(false) is called
}
};
我尝试过 Julien Ripet 的回答,但遇到了同样的问题。 现在使用该代码:
const [animAttrs, setAnimAttrs] = useState({isLoading: false, mod: null, index: null});
const changeItemHandler = (mod, index) => {
if (animAttrs.isLoading === true) return;
else setAnimAttrs({ isLoading: true, mod: mod, index: index });
};
useEffect(() => {
if (animAttrs.mod == null) return;
//needed to not call this function only after click or swipe
else changeItem(animAttrs.mod, animAttrs.index);
//onanimationend i call setAnimAttrs({isLoading:false,mod:null,index:null});
}, [animAttrs]);
即使 animAttrs.isLoading === true,它也会调用 changeItem 函数。我无法解释这种行为。
【问题讨论】:
-
我需要知道动画是否正在播放。如果我只允许函数在动画结束时运行,我最初将无法运行它。并且 onStart 几乎在单击按钮的同时发生,因此也没有用。我也不知道如何使用动画迭代事件,因为如果我只是检查它是否存在,我可能不会进入交互实际触发的那一刻。感谢您的尝试!
-
我认为你的组件在应用动画后会重新渲染。
-
动画结束后会重新渲染。但这有什么帮助呢?
标签: javascript reactjs