2017-01-04 101 views
2

我更改了通過時間間隔呈現的組件。反應:如何動畫渲染組件的變化?

我希望每次發生更改時都能夠添加動畫。什麼是最好的方式去做呢?

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

編輯:

也在試圖利用 '反應 - 插件 - CSS-過渡小組' 時,我得到了以下錯誤:

enter image description here

+0

在我看來,最簡單的就是使用CSS3過渡。你根據你的狀態給你的元素一個類,這會改變元素的樣式。您可以使用CSS3轉換(或CSS3動畫)轉換此樣式。 – stinodes

回答

1

你可以用ReactCSSTransitionGroup做像這樣提供的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> 

    ) 
    } 
} 
+1

謝謝。多數民衆贊成我試圖但每次我導入該圖書館。我不斷收到以下錯誤: 未捕獲TypeError:React.PropTypes.shape不是函數 –

+0

此錯誤可能是其他地方...您在哪裏應用中有Protypes定義? –

+0

我真的從圖書館得到它。我在帖子中添加了錯誤截圖。 –