我正在尝试找出在事件触发后从 DOM 中删除元素的 React 方法。
我正在尝试发出警报(copySuccess
) when onClick={this.props.handleCopyFact}
被触发,然后在 5 秒后淡出该警报。每个组件的状态都在父组件中设置。
这是我的组件的代码:
module.exports = React.createClass({
render: function() {
var copy = null;
if (!this.props.copying && !this.props.editting) {
copy = (
<div className="copy-fact-container" onClick={this.props.handleCopyFact}>
<i className="icon-copy"></i>
<span>Copy</span>
</div>
);
}
var copySuccess = null;
if (this.props.copySuccess) {
copySuccess = (
<div className="copy-success">
<div><i className="icon icon-clipboard"></i></div>
<p className="heading">Copied to Clipboard</p>
</div>
);
}
return (
<div className="row-body"
onMouseEnter={this.props.toggleCopyFact}
onMouseLeave={this.props.toggleCopyFact}>
<MDEditor editting={this.props.editting}
content={this.props.content}
changeContent={this.props.changeContent}/>
{copy}
{copySuccess}
</div>
);
}
});
一种方法是创建一个 Expire 组件,该组件将在延迟后隐藏其子组件。您可以将其与 CSSTransitionGroup 结合使用来执行淡出行为。
jsbin http://jsbin.com/zomiloma/3/edit?js,output
Usage:
render: function(){
return <Expire delay={5000}>This is an alert</Expire>
}
组件:
var Expire = React.createClass({
getDefaultProps: function() {
return {delay: 1000};
},
getInitialState: function(){
return {visible: true};
},
componentWillReceiveProps: function(nextProps) {
// reset the timer if children are changed
if (nextProps.children !== this.props.children) {
this.setTimer();
this.setState({visible: true});
}
},
componentDidMount: function() {
this.setTimer();
},
setTimer: function() {
// clear any existing timer
this._timer != null ? clearTimeout(this._timer) : null;
// hide after `delay` milliseconds
this._timer = setTimeout(function(){
this.setState({visible: false});
this._timer = null;
}.bind(this), this.props.delay);
},
componentWillUnmount: function() {
clearTimeout(this._timer);
},
render: function() {
return this.state.visible
? <div>{this.props.children}</div>
: <span />;
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)