1.下载react-transition-group

  1. yarn add react-transition-group

2.使用

  1. import React, { PureComponent } from 'react'
  2. import {SwitchTransition,CSSTransition}from 'react-transition-group'
  3. import "./index.css"
  4. export default class index extends PureComponent {
  5. state={
  6. isOn:true
  7. }
  8. render() {
  9. const {isOn}=this.state
  10. return (
  11. <div style={{padding:'20px'}}>
  12. <SwitchTransition>
  13. <CSSTransition key={isOn?'on':'off'} classNames='btn' timeout={1000}>
  14. <button onClick={e=>this.setState({isOn:!isOn})}>{isOn?'on':'off'}</button>
  15. </CSSTransition>
  16. </SwitchTransition>
  17. </div>
  18. )
  19. }
  20. }
  1. //index.css
  2. .btn-enterr{
  3. opacity: 0;
  4. transform: translateX(100%);
  5. }
  6. .btn-enter-active{
  7. opacity: 1;
  8. transform: translateX(0);
  9. transition: all 1000ms;
  10. }
  11. .btn-enter-done{
  12. }
  13. .btn-exit {
  14. opacity: 1;
  15. }
  16. .btn-exit-active {
  17. opacity: 0;
  18. transform: translateX(-100%);
  19. transition: all 1000ms;
  20. }
  21. .btn-exit-done {
  22. opacity: 0;
  23. }