如何动画渲染组件的更改

如何动画渲染组件的更改

本文介绍了React:如何动画渲染组件的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I change the component that is rendered through a time interval.

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

I would like to be able to add an animation every time that change happens. What is the best way to go about it?

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'
时,我得到以下内容错误:

Also when trying to use 'react-addons-css-transition-group'I get the following error:

推荐答案

您可以使用此中提供的ReactCSSTransitionGroup

You can do with ReactCSSTransitionGroup like provided in this section

你的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>

    )
  }
}

这篇关于React:如何动画渲染组件的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:33