我正在使用React Router 4和React Transition Group 2. *我无法将其设置为在页面更改时进行退出转换/动画。如果我记录转换事件,我只会获得退出事件,该事件会在我开始页面转换后立即触发。
淡入淡出过渡:
import React, { Component } from 'react'
import Transition, {
ENTERING,
ENTERED,
EXITING,
EXITED,
} from 'react-transition-group/Transition'
// can be set globaly, just duration = 500
const duration = 300
const defaultStyle = {
transition: `all ${duration}ms ease-in-out`,
color: 'white',
opacity: 0,
marginTop: '82px',
}
const transitionStyles = {
[ENTERING]: {
opacity: 0,
marginTop: '82px',
},
[ENTERED]: {
opacity: 1,
marginTop: '62px',
},
[EXITING]: {
opacity: 1,
marginTop: '62px',
},
[EXITED]: {
opacity: 0,
marginTop: '82px',
},
}
class FadeTransition extends Component {
handleExit = elem => {
console.log('handleExit')
}
handleExiting = elem => {
console.log('handleExiting')
}
render() {
const { in: inProp, children } = this.props
return (
<Transition
in={inProp}
timeout={duration}
appear={true}
exit={false}
onExit={this.handleExit}
onExiting={this.handleExiting}
>
{(state, props) =>
React.cloneElement(children, {
...props,
style: {
...defaultStyle,
...transitionStyles[state],
},
})}
</Transition>
)
}
}
export default FadeTransition
App.js文件:
class App extends Component {
render() {
return (
<div className="App">
<div className="TopBar">
<Link to="/">Home</Link>
<Link to="/subpage">Subpage</Link>
</div>
<Route
{...this.props}
render={({ location }) =>
<TransitionGroup component="main">
<FadeTransition in={false}>
<Switch location={location} key={location.key}>
<Route
exact
path="/"
children={({ match, ...rest }) => <Home {...rest} />}
/>
<Route
path="/subpage"
children={({ match, ...rest }) => <Subpage {...rest} />}
/>
</Switch>
</FadeTransition>
</TransitionGroup>}
/>
</div>
)
}
}
最后,主页文件:
class Home extends Component {
render() {
return (
<FadeTransition in={true} key={'home'}>
<div className="page">
<h1>Home</h1>
<p>Hello from the home page!</p>
</div>
</FadeTransition>
)
}
}
答案 0 :(得分:2)
您应该在FadeTransition
组件上添加密钥,以便TransitionGroup
看到子项已更改并触发动画
应该看起来像这样
<TransitionGroup className="page-animation-container">
<FadeTransition key={location.key} in={false}>
<Switch location={location}>
<Route
exact
path="/"
children={({ match, ...rest }) => <Home {...rest} />}
/>
<Route
path="/subpage"
children={({ match, ...rest }) => <Subpage {...rest} />}
/>
</Switch>
</FadeTransition>
</TransitionGroup>