这有点冗长,但是我使用了所有本机事件和方法来实现此动画。否
ReactCSSTransitionGroup,
ReactTransitionGroup等等。
我用过的东西
- 反应生命周期方法
onTransitionEnd
事件
如何运作
- 根据通过的挂载道具(
mounted
)和默认样式(opacity: 0
)来挂载元素 - 挂载或更新后,使用
componentDidMount
(componentWillReceiveProps
用于进一步更新)更改样式(opacity: 1
)并带有超时(以使其异步)。 - 在卸载过程中,将prop传递给组件以识别卸载,再次更改样式(
opacity: 0
),onTransitionEnd
然后从DOM中移除元素。
继续循环。
查看代码,您会明白的。如果需要任何澄清,请发表评论。
希望这可以帮助。
class App extends React.Component{ constructor(props) { super(props) this.transitionEnd = this.transitionEnd.bind(this) this.mountStyle = this.mountStyle.bind(this) this.unMountStyle = this.unMountStyle.bind(this) this.state ={ //base css show: true, style :{ fontSize: 60, opacity: 0, transition: 'all 2s ease', } } } componentWillReceiveProps(newProps) { // check for the mounted props if(!newProps.mounted) return this.unMountStyle() // call outro animation when mounted prop is false this.setState({ // remount the node when the mounted prop is true show: true }) setTimeout(this.mountStyle, 10) // call the into animation } unMountStyle() { // css for unmount animation this.setState({ style: { fontSize: 60, opacity: 0, transition: 'all 1s ease', } }) } mountStyle() { // css for mount animation this.setState({ style: { fontSize: 60, opacity: 1, transition: 'all 1s ease', } }) } componentDidMount(){ setTimeout(this.mountStyle, 10) // call the into animation } transitionEnd(){ if(!this.props.mounted){ // remove the node on transition end when the mounted prop is false this.setState({ show: false }) } } render() { return this.state.show && <h1 style={this.state.style} onTransitionEnd={this.transitionEnd}>Hello</h1> }}class Parent extends React.Component{ constructor(props){ super(props) this.buttonClick = this.buttonClick.bind(this) this.state = { showChild: true, } } buttonClick(){ this.setState({ showChild: !this.state.showChild }) } render(){ return <div> <App onTransitionEnd={this.transitionEnd} mounted={this.state.showChild}/> <button onClick={this.buttonClick}>{this.state.showChild ? 'Unmount': 'Mount'}</button> </div> }}ReactDOM.render(<Parent />, document.getElementById('app'))<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-with-addons.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="app"></div>


