我想在两个组件之间进行动画处理,第一个组件淡出并从DOM中删除,然后再将下一个组件添加到DOM中并淡入。否则,新组件将添加到DOM中并占用空间。旧组件已删除。您可以在这个小提琴中看到问题:
http://jsfiddle.net/phepyezx/4
// css snippet .switch-enter { opacity: 0.01; } .switch-enter.switch-enter-active { opacity: 1.0; } .switch-leave { opacity: 1.0; } .switch-leave.switch-leave-active { opacity: 0; } // React snippet <ReactCSSTransitionGroup transitionName="switch"> <div key={key} className={className}>{this.text()}</div> </ReactCSSTransitionGroup>
对于我来说,不可接受的解决方案是在转换为新组件之前用CSS隐藏原始组件,如下所示:
http://jsfiddle.net/phepyezx/5
// Change to css .switch-leave { visibility: hidden; height: 0px; width: 0px; opacity: 1.0; }
有没有办法在拆下原始组件之前“延迟”安装新组件的反应?我对速度或其他库持开放态度。
谢谢
使用componentWillUnmount()生命周期方法解决。
componentWillUnmount()
http://jsfiddle.net/phepyezx/9/
这是代码:
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; const Off = React.createClass({ componentWillUnmount () { this.props.handleTransitionEnd(); }, render() { return ( <div className="off button">OFF</div> ) } }); const On = React.createClass({ componentWillUnmount () { this.props.handleTransitionEnd(); }, render() { return ( <div className="on button">ON</div> ) } }); var Switch = React.createClass({ getInitialState: function() { return { on: false, transitionEnd: true }; }, toggle: function(e) { this.setState({ on: !this.state.on, transitionEnd: false }); }, handleTransitionEnd() { this.setState({transitionEnd: true}); }, renderOff() { if (! this.state.on && this.state.transitionEnd) { return ( <Off key="off" handleTransitionEnd={this.handleTransitionEnd} /> ) } }, renderOn() { if (this.state.on && this.state.transitionEnd) { return ( <On key="on" handleTransitionEnd={this.handleTransitionEnd} /> ) } }, render: function() { return ( <div> <button onClick={this.toggle}>Toggle</button> <ReactCSSTransitionGroup transitionName="switch"> {this.renderOff()} {this.renderOn()} </ReactCSSTransitionGroup> </div> ); } }); React.render(<Switch/>, document.getElementById("switch"));
和相关的CSS:
.switch-enter { opacity: 0.01; } .switch-enter.switch-enter-active { opacity: 1.0; transition: opacity 500ms ease-in; } .switch-leave { opacity: 1.0; } .switch-leave.switch-leave-active { opacity: 0; transition: opacity 500ms ease-out; }
您可以使用onnyBuchanan的答案获得相同的有效结果,该答案使用绝对定位和延迟而不是componentWillUnmount()