Page transitions AND component animation in ReactJ

2019-07-15 05:48发布

问题:

My desired affect:

  • When the page loads components A, B and C animate on independently
  • The user clicks a link inside, say, component B
  • Components A, B and C animate off independently
  • A new page loads, more components animate on.

This sounds simple but I'm struggling to make it happen. So far I have a number of routes setup using react-router v4 and I am using CSSTransitionGroup to add movement to routes and components.

The problem I am having is:

  • If a route is animated, I cannot seem to animate anything inside the component which is called. Certainly, the animation for when a component leaves will not work.
  • If a component alone is animated (and not the route), when the route changes there is no delay for any animation to occur.

Any hints or resources on how to achieve this desired affect would be great!

TL;DR: transitionLeaveTimeout is not being applied to animated components inside an animated route.

回答1:

I've found a solution, but it's not particularly elegant.

In brief, the problem occurred because any components which are rendered by a route technically only ever appear. So what I had to do was use the route's render function, like so:

<CSSTransitionGroup
transitionName="test"
transitionAppear={true}
transitionAppearTimeout={1000}
transitionEnterTimeout={1000}
transitionLeaveTimeout={1000}>

<Route exact path="/about" location={this.props.location} key={this.props.location.key} render={({ location }) => (

    <CSSTransitionGroup
    transitionName="test2"
    transitionAppear={true}
    transitionAppearTimeout={2000}
    transitionEnterTimeout={1000}
    transitionLeaveTimeout={1000}>

        <AboutBox key={this.props.location.key} />

    </CSSTransitionGroup>

)} />

</CSSTransitionGroup>

So what is happening here is:

  • The route is wrapped in a transition group, which means it animates on appear, enter and leave
  • The route itself is NOT using component=, it is using a render function (render=) to call the component (AboutBox)
  • Because this too is wrapped in a transition group, it can be animated on appear, enter and leave

If I were to move that transition group to the component itself, only appear would be available to it.

Hope this helps somebody!