简体   繁体   中英

Fading a component in and fading another one out React.js

I just recently started getting into using React.js and to make it easier for myself I'm trying to recreate projects I've made in the past, but instead of using jQuery like I did in the past I'm completely avoiding jQuery and using only React.

I tend to do animations where a div would fade in as another fades out like this:

$("#start").click(function() {
    $("#h1").fadeOut(750);
    $("#h2").delay(500).fadeIn(750);
    $("#h1").css("z-index", 0);
    $("#h2").css("z-index", 1);
}); 

I was wondering how can I reproduce this fade in and out effect without jQuery

(I know CSS animations could change the opacity, but the opacity isn't the only thing I'm trying to change, this affects the display property as well).

One option would be to use a framework, like react-bootstrap, which includes a lot of the UI components you need for any given project. It includes a Fade component. Documentation can be found here: https://react-bootstrap.github.io/components.html#utilities

class Example extends React.Component {

 constructor(...args) {
  super(...args);
  this.state = {};
 }

 render() {
  return (
    <div>
      <Button onClick={()=> this.setState({ open: !this.state.open })}>
       click
      </Button>
      <Fade in={this.state.open}>
        <div>
          <Well>
            THIS CONTENT WILL FADE
          </Well>
        </div>
      </Fade>
    </div>
  );
 }
}

ReactDOM.render(<Example/>, mountNode);

A simple way is to use CSS transitions. Basically you just add a class to an element, and define a transition in the CSS and it does the rest for you

There is a tutorial here

https://www.w3schools.com/css/css3_transitions.asp

Which does a good job of explaining how it all works with examples and a playground for you to try your own

The CSS Transition group add-on might help, it let's you define transitions like this:

JS:

<ReactCSSTransitionGroup
  transitionName="example"
  transitionEnterTimeout={500}
  transitionLeaveTimeout={300}>
  {items}
</ReactCSSTransitionGroup>

CSS:

.example-enter {
  opacity: 0.01;
}

.example-enter.example-enter-active {
  opacity: 1;
  transition: opacity 500ms ease-in;
}

.example-leave {
  opacity: 1;
}

.example-leave.example-leave-active {
  opacity: 0.01;
  transition: opacity 300ms ease-in;
}

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