简体   繁体   中英

Removing element from DOM after set amount of time

I'm trying to figure out the React way to remove an element from the DOM after an event if fired.

I am attempting to flash an alert ( copySuccess ) when onClick={this.props.handleCopyFact} is fired, and then fade that alert out after 5 seconds. The state of each of these are set within a parent component.

Here is the code for my component:

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>
);
}
});

One way is to create an Expire component which will hide its children after a delay. You can use this in conjunction with a CSSTransitionGroup to do the fade out behavior.

jsbin

Usage:

render: function(){
    return <Expire delay={5000}>This is an alert</Expire>
}

The component:

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 />;
  }
});

Updated @FakeRainBrigand 's answer to support a more modern React syntax that uses a class in lieu of the deprecated React.createComponent method.

class Expire extends React.Component {
  constructor(props) {
    super(props);
    this.state = {visible:true}
  }

  componentWillReceiveProps(nextProps) {
    // reset the timer if children are changed
    if (nextProps.children !== this.props.children) {
      this.setTimer();
      this.setState({visible: true});
    }
  }

  componentDidMount() {
    this.setTimer();
  }

  setTimer() {
    // clear any existing timer
    if (this._timer != null) {
      clearTimeout(this._timer)
    }

    // hide after `delay` milliseconds
    this._timer = setTimeout(function(){
      this.setState({visible: false});
      this._timer = null;
    }.bind(this), this.props.delay);
  }

  componentWillUnmount() {
    clearTimeout(this._timer);
  }

  render() {
    return this.state.visible
      ? <div>{this.props.children}</div>
      : <span />;
  }
}

Furthermore simplified way using Hooks .

From React Hooks docs,

useEffect hook combinely does all these three componentDidMount , componentDidUpdate , and componentWillUnmount

Your Expire component should be

import React, { useEffect, useState } from "react";

const Expire = props => {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setVisible(false);
    }, props.delay);
  }, [props.delay]);

  return visible ? <div>{props.children}</div> : <div />;
};

export default Expire;

Now, pass the delay prop in Expire component.

<Expire delay="5000">Hooks are awesome!</Expire>

I created a working example using Codesandbox

Updated @pyRabbit to use the newer React hooks and a prop field to toggle the visibility of a children component:

const DelayedToggle = ({ children, delay, show }) => {
  let timer = null;

  // First, set the internal `visible` state to negate 
  // the provided `show` prop
  const [visible, setVisible] = useState(!show);

  // Call `setTimer` every time `show` changes, which is
  // controlled by the parent.
  useEffect(() => {
    setTimer();
  }, [show]);

  function setTimer() {
    // clear any existing timer
    if (timer != null) {
      clearTimeout(timer)
    }

    // hide after `delay` milliseconds
    timer = setTimeout(() => {
      setVisible(!visible);
      timer = null;
    }, delay);
  }

  // Here use a `Fade` component from Material UI library
  // to create a fade-in and -out effect.
  return visible 
    ?
    <Fade in={show} timeout={{
      enter: delay + 50,
      exit: delay - 50,
    }}
    >
      {children}
    </Fade>
    : <span />;
};

const Parent = () => {
  const [show, setShow] = useState(false);
  return (
    <>
      <button onClick={() => setShow(!show)}>toggle</button>
      <DelayedToggle 
        delay={300} 
        show={show}
        children={<div><h1>Hello</h1></div>}
      />
    </>
  )
};

编辑 Peace-galileo-hvqb5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM