反应生命周期事件取消 GSAP 动画



我正在尝试将 GSAP 与 React 一起使用,但我遇到了我的动画被取消的情况。

我的组件是一个侧边栏,仅当状态中的"show"属性为真时才会出现。在组件内部,我的主要功能是:

shouldComponentUpdate(nextProps, nextState) { 
return nextState.show !== this.state.show; 
}
componentWillUpdate(nextProps, nextState) {
if (nextState == true) {
// animate the sidebar in
} else {
// animate the sidebar out
}
}
toggleSidebar() { 
const newState = !this.state.show;
this.setState({ show: newState })
}

出于某种原因,当我单击按钮以触发切换侧边栏功能时,侧边栏开始动画化,然后立即动画化。

我有一种感觉,因为组件WillUpdate返回得太快了,但我不确定。

在这一点上,我正在考虑只使用 TransitionGroup 并将 GSAP 动画代码包含在组件 WillEnter/componentWillLeave 生命周期钩子中,以便它们可以正常运行,但我很好奇是否有任何方法可以解决这个问题。

一个常见的原因是toggleSidebar被调用两次。Safari浏览器有时会发生这种情况,但我也在Chrome浏览器中看到了一些情况。您可以尝试通过按钮单击在接收事件上使用e.preventDefault,也可以使用旧时尚布尔标志,例如

toggleSidebar() {
if (isAnimating) {
isAnimating = !isAnimating;
return;
}
isAnimating = true;
const newState = !this.state.show;
this.setState({
show: newState
})
}

最新更新