javascript - FadeIn and FadeOut effect using React JS - Stack Overflow

I have something like this :var Hello = React.createClass({getInitialState: function(){return {opacity:

I have something like this :

var Hello = React.createClass({
    getInitialState: function(){
    return {
        opacity: 0
    }
  },

  handleClick: function(event){
    event.preventDefault();
    this.setState({opacity: 1});
  },

  render: function() {
    return <div>
        <div style={{opacity: this.state.opacity, transition: "opacity 1s"}}>Test</div>
      <a href="" onClick={this.handleClick}>Click</a>
    </div>;
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

Here is jsfiddle

I want that div with text test within doesn't shows up on page load. Then if I click on the link that that div shows up. That is what this example do.

But I want that after the div shows up after the click, a few seconds later it disappears again. (I need somehow set opacity to 0 again).

Any advice?

I have something like this :

var Hello = React.createClass({
    getInitialState: function(){
    return {
        opacity: 0
    }
  },

  handleClick: function(event){
    event.preventDefault();
    this.setState({opacity: 1});
  },

  render: function() {
    return <div>
        <div style={{opacity: this.state.opacity, transition: "opacity 1s"}}>Test</div>
      <a href="" onClick={this.handleClick}>Click</a>
    </div>;
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

Here is jsfiddle

I want that div with text test within doesn't shows up on page load. Then if I click on the link that that div shows up. That is what this example do.

But I want that after the div shows up after the click, a few seconds later it disappears again. (I need somehow set opacity to 0 again).

Any advice?

Share Improve this question asked Aug 5, 2016 at 12:12 BokyBoky 12.1k30 gold badges101 silver badges172 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

You can add the FadeOut effect passing a callback function to setState().

A simple solution would look like this

handleClick: function(event){
    event.preventDefault();
    this.setState({opacity: 1}, () => setTimeout(() => this.setState({opacity:0}),4000)); 
},

jsfiddle

A better one would be

handleClick: function(event){
    event.preventDefault();
    this.setState({opacity: 1}, () => {
        if(!this.timeout)
            clearTimeout(this.timeout);
        this.timeout = setTimeout(() => this.setState({opacity:0}),4000);
 });

jsfiddle

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745088227a4610534.html

相关推荐

  • javascript - FadeIn and FadeOut effect using React JS - Stack Overflow

    I have something like this :var Hello = React.createClass({getInitialState: function(){return {opacity:

    18小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信