Подтвердить что ты не робот

Удаление элемента из DOM после установленного количества времени

Я пытаюсь выяснить способ React удалить элемент из DOM после события, если оно запущено.

Я пытаюсь вывести предупреждение (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>
);
}
});
4b9b3361

Ответ 1

Один из способов - создать компонент 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 />;
  }
});