我试图找出一种事件触发后从DOM中删除元素的React方法。
我尝试在触发copySuccess
时刷新警报(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
用法:
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 />;
}
});
关于javascript - 设置时间后从DOM中删除元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24171226/