Transition Group没有触发生命周期方法

时间:2017-05-04 20:16:42

标签: reactjs gsap

我在进入和离开DOM时在一些React组件上运行一些GSAP动画。我目前遇到的问题是只有第一个组件似乎触发了输入动画。第一个组件不会触发离开动画,其余组件不会触发任何动画。

以下相关代码

class Home extends React.Component {
  render() {
    const { lastActive, activeSection } = this.state;

    let fullSection = null;
    switch(activeSection) {
      case 1:
        fullSection = <SlideOne enterFromTwo={lastActive === 2 && activeSection === 1} />
        break;

      case 2:
        fullSection = <SlideFour />
        break;

      default:
        return false;
    }

    return (
      <TransitionGroup>
        {fullSection}
      </TransitionGroup>
    )
  }
}

现在为Slide 1

class SlideOne extends Component {

  componentWillEnter() {
    console.log('component will enter');
  }

  componentWillAppear(callback) {
    console.log('component will appear');

    if (!this.props.enterFromTwo) {
      this.addAnimation(this.enterAnimation, {callback: callback});
    } else {
      callback();
    }
  }

  componentWillLeave(callback) {
    console.log('component will leave');
    callback();
  }

  enterAnimation({target, options}) {
    const title = target.find({name: 'title'});
    const tl = new TimelineMax({onComplete: options.callback});

    return tl.from(title, 3, {
      autoAlpha: 0,
      ease: Power2.easeIn
    });
  }


  render() {
    return (
      <FullSection>
        <BorderedTitle name="title">connecting the music industry</BorderedTitle>
      </FullSection>
    );
  }
}

当从DOM中删除Slide one时,将永远不会调用Component Will Leave生命周期方法。

有没有人知道为什么会出现这种情况。

1 个答案:

答案 0 :(得分:1)

您需要确保您想要展示的任何反应元素具有唯一键,即使它是单个项目。

e.g。

<SlideOne key={ somethingUnique }/><SlideFour key={ somethingUnique }/> - 只要唯一键是稳定的。

当我只关心低级API https://facebook.github.io/react/docs/animation.html#low-level-api-reacttransitiongroup

时,我显然忽略了这一点

反应文档:

  

注意:   您必须为ReactCSSTransitionGroup的所有子项提供key属性,即使只渲染单个项目也是如此。这就是React将如何确定哪些孩子已进入,离开或留下。

https://facebook.github.io/react/docs/animation.html

相关问题