我正在使用 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>
)
}
}