【问题标题】:React lifecycle events cancel GSAP animationReact 生命周期事件取消 GSAP 动画
【发布时间】:2017-07-25 18:08:58
【问题描述】:

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

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

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 })
}

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

我有一种感觉,因为 componentWillUpdate 返回太快,但我不确定。

此时,我正在考虑仅使用 TransitionGroup 并将 GSAP 动画代码包含在 componentWillEnter / componentWillLeave 生命周期挂钩中,以便它们可以正常运行,但我很好奇是否有任何方法可以解决此问题。

【问题讨论】:

  • 如果可能,请始终使用 DidWill 可能会产生一些令人讨厌的副作用。

标签: reactjs animation gsap


【解决方案1】:

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

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

【讨论】:

  • 嗯,我尝试了从 toggleMenu 记录的方法和控制台,似乎只调用了一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多