React:如何动画渲染组件的更改?

时间:2017-01-04 20:35:26

标签: javascript css reactjs animation

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

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

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
    )
}

编辑:

当尝试使用&#39; react-addons-css-transition-group&#39; 我收到以下错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用此section

中提供的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>

    )
  }
}