javascript - 在设定的时间后从 DOM 中删除元素

标签 javascript reactjs

我正在尝试找出在触发事件后从 DOM 中删除元素的 React 方法。

onClick={this.props.handleCopyFact} 被触发时,我试图闪烁警报 (copySuccess),然后在 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/

相关文章:

javascript - NPM 或任何其他包的名称和任何版本号的正则表达式

node.js - Create-react-app npm run build 太慢

javascript - Next Js 结合外部 REST API 身份验证和授权

javascript - javascript 应该如何集成到 Clojure/Ring 网络应用程序中?

javascript - 如何通过 knockout 部分(重新)将绑定(bind)应用于后代?

javascript - 揭露面膜CSS

javascript - 使用显示模板显示随机图像

node.js - 使用 React 和 Socket.io 的聊天应用程序在发送过多消息后挂起

javascript - 如何访问 map 函数中变量的值?

reactjs - 如何在不触发 useEffect 的情况下触发状态更新