React:如何动画化呈现组件的变化?

IT技术 javascript css reactjs animation
2021-05-09 20:22:05

我更改了通过时间间隔呈现的组件。

我希望能够在每次发生变化时添加动画。最好的方法是什么?

constructor (props) {
    super(props)
    this.state = { currentComponent: 1,
    numberOfComponents: 2}
}

componentWillMount() {
    setInterval(() => {
       if(this.state.currentComponent === 2) {
           this.setState({currentComponent: 1})
       } else {
           this.setState({currentComponent: this.state.currentComponent + 1})
       }
    }, 5000)
}

render(){

    let currentComponent = null;

    if(this.state.currentComponent === 1) {
        currentComponent = <ComponentOne/>;

    } else {
        currentComponent = <ComponentTwo/>;
    }

    return(
        currentComponent
    )
}

编辑:

此外,当尝试使用“react-addons-css-transition-group”时,我收到以下错误:

在此处输入图片说明

1个回答

你可以像本提供的那样使用 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;
}

看起来像这样:

import ReactCSSTransitionGroup from 'react-addons-css-transition-group';



class MyComponent extends Component {
  constructor (props) {
    super(props)
    this.state = { currentComponent: 1,
    numberOfComponents: 2}
  }

  componentWillMount() {
    setInterval(() => {
       if(this.state.currentComponent === 2) {
           this.setState({currentComponent: 1})
       } else {
           this.setState({currentComponent: this.state.currentComponent + 1})
       }
    }, 5000)
  }

  render(){

    let currentComponent = null;

    if(this.state.currentComponent === 1) {
        currentComponent = <ComponentOne/>;

    } else {
        currentComponent = <ComponentTwo/>;
    }

    return(
        <ReactCSSTransitionGroup
          transitionName="example"
           transitionEnterTimeout={500}
          transitionLeaveTimeout={300}>
          {currentComponent}
        </ReactCSSTransitionGroup>

    )
  }
}