使用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;
}
您可以使用Jonny Buchanan 的答案获得相同的有效结果,该答案使用绝对定位和延迟而不是componentWillUnmount()