2016-03-02 82 views
6

使用React Motion's TransitionMotion,我想動畫1個或多個框進出。當一個盒子進入視圖時,它的寬度和高度應該從0像素到200像素,並且不透明度應該從0到1.當盒子離開視圖時,應該發生逆轉(寬度/高度= 0,不透明度= 0 )如何使用React TransitionMotion將輸入()

我試圖在這裏解決這個問題http://codepen.io/danijel/pen/RaboxO但我的代碼無法正確轉換框。盒子的樣式立即跳到200像素的寬度/高度,而不是過渡。

代碼有什麼問題?

let Motion = ReactMotion.Motion 
let TransitionMotion = ReactMotion.TransitionMotion 
let spring = ReactMotion.spring 
let presets = ReactMotion.presets 

const Demo = React.createClass({ 
    getInitialState() { 
    return { 
     items: [] 
    } 
    }, 
    componentDidMount() { 

    let ctr = 0 

    setInterval(() => { 
     ctr++ 
     console.log(ctr) 
     if (ctr % 2 == 0) { 
     this.setState({ 
      items: [{key: 'b', width: 200, height: 200, opacity: 1}], // fade box in 
     }); 
     } else { 
     this.setState({ 
      items: [], // fade box out 
     }); 
     } 

    }, 1000) 
    }, 
    willLeave() { 
    // triggered when c's gone. Keeping c until its width/height reach 0. 
    return {width: spring(0), height: spring(0), opacity: spring(0)}; 
    }, 

    willEnter() { 
    return {width: 0, height: 0, opacity: 1}; 
    }, 

    render() { 
    return (
     <TransitionMotion 
     willEnter={this.willEnter} 
     willLeave={this.willLeave} 
     defaultStyles={this.state.items.map(item => ({ 
      key: item.key, 
      style: { 
      width: 0, 
      height: 0, 
      opacity: 0 
      }, 
     }))} 
     styles={this.state.items.map(item => ({ 
      key: item.key, 
      style: { 
      width: item.width, 
      height: item.height, 
      opacity: item.opacity 
      }, 
     }))} 
     > 
     {interpolatedStyles => 
      <div> 
      {interpolatedStyles.map(config => { 
       return <div key={config.key} style={{...config.style, backgroundColor: 'yellow'}}> 
       <div className="label">{config.style.width}</div> 
       </div> 
      })} 
      </div> 
     } 
     </TransitionMotion> 
    ); 
    }, 
}); 

ReactDOM.render(<Demo />, document.getElementById('app')); 

回答

8

爲每stylesdocumentationTransitionMotion部分(我不聲稱已經完全瞭解這一切:)):

風格:...數組TransitionStyle的...

這裏要注意的關鍵一點是,有2種風格的對象,這個庫處理(或至少這TransitionMotion部分),它稱它們爲TransitionStyleTransitionPlainStyle

傳遞到styles屬性中的以前的值爲TransitionPlainStyle。將它們更改爲TransitionStyle神奇開始動畫Enter序列。

您可以通過here瞭解更多關於上述2種不同類型的信息。

styles={this.state.items.map(item => ({ 
    key: item.key, 
    style: { 
    width: spring(item.width), 
    height: spring(item.height), 
    opacity: spring(item.opacity) 
    } 
}))} 

Forked codepen demo

同樣,我還沒有完全理解它的內部工作原理。我只知道你的styles必須按照上述方式進行更改才能使其正常工作。

如果有人能夠教育我,我會很高興。

希望這會有所幫助。

+0

很好的解釋。謝謝Tahir。 – Learner

相關問題