[三元學React]使用react-transition-group開發React動畫

1、安裝並引入第三方庫

npm install react-transition-group --save
複製代碼

2、對一個元素開發動畫

首先利用CSSTransition進行單個元素的動畫開發。css

//App.js
import { CSSTransition } from 'react-transition-group'
import React, { Component } from 'react';
import './style.css'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      isShow: true
    }
    this.toToggole = this.toToggole.bind(this)
  }
  render() { 
    return ( 
      <div> <CSSTransition <!-- in表示是否出現 timeout表示動畫延時 --> in={this.state.isShow} timeout={2000} <!-- classNames是鉤子名,爲後面的class名前綴 --> classNames="test" <!-- unmountOnExit表示元素隱藏則相應的DOM被移除 --> unmountOnExit <!-- appear設爲true表示進場動畫,CSS中有對應類名 --> appear={true} <!--如下爲動畫鉤子函數, 與CSS中相對應--> onEnter={(el) => {}} onEntering={(el) => {}} onEntered={(el) => {}} onExit={(el) => {}} onExiting={(el) => {}} onExited={(el) => {}} > <div>hello</div> </CSSTransition> <div><button onClick={this.toToggole}>點我</button></div> </div>  
    );
  }
  toToggole() {
    this.setState({
      isShow: !this.state.isShow
    })
  }
}
 
export default App;
複製代碼
//進場前的瞬間
.test-enter, .test-appear{
    opacity: 0;
}
//進場過程當中
.test-enter-active, .test-appear-active{
    opacity: 1;
    transition: opacity 2000ms;
}
//進場以後
.test-enter-done{
    opacity: 1;
}
//離開前的瞬間
.test-exit{
    opacity: 1;
}
//離開過程當中
.test-exit-active{
    opacity: 0;
    transition: opacity 2000ms;
}
//離開後
.test-exit-done{
    opacity: 0;
}
複製代碼

3、對一組元素進行動畫操做

//App.js
//CSS文件和style.css相同
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import React, { Component } from 'react';
import './style.css'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      list: []
    }
    this.handleAddItem = this.handleAddItem.bind(this)
  }
  render() { 
    return ( 
      <div> <TransitionGroup> { this.state.list.map((item, index) => { return ( <CSSTransition timeout={2000} classNames="test" unmountOnExit onEntered={(el) => {el.style.color='blue'}} appear={true} > <div key={index}>{item}</div> </CSSTransition> ) }) } </TransitionGroup> <div><button onClick={this.handleAddItem}>點我</button></div> </div>  
    );
  }
  handleAddItem() {
    this.setState((prevState) => {
      return {
        list: [...prevState.list, 'item']
      }
    })
  }
}
 
export default App;
複製代碼

今天解鎖了react使用動畫的新姿式,記錄一下,但願對你們有幫助。react

相關文章
相關標籤/搜索