關於react 動畫組件已經有不少,最近想本身作一個,目的就是依賴css3動畫,這樣能保證性能,項目種簡單動畫足夠了;若是要複雜一些的動畫,那就依賴於js了,本篇主要實現一個Animate組件,給組件內部添加元素的入場動畫和出場動畫,因而就花費半天時間試試,主要採用animate.css,你們必定很熟悉,下面就是思路和代碼,確定有須要完善的地方,請各位大神批評指導。css
首先要引入 animate.cssreact
import React from 'react'; export default class Animate extends React.Component { state = { animateName: '',//切換動畫class名稱 animateChild: null,//作一個緩存 } currentTime = new Date() componentWillReceiveProps(nextProps) { let prevChild = this.props.children let nextChild = nextProps.children let { enterClass, leaveClass } = this.props let expirationTime = new Date() if(!this._isExpiration(expirationTime)){ return }//防止過快點擊 this.currentTime = expirationTime if(nextChild !== null){ this.setState({ animateChild: nextChild, animateName: enterClass, }) } else if (prevChild !== null) { this.setState({ animateName: leaveClass, }) setTimeout(()=>{ this.setState({ animateChild: null, }) },500)// 離場延遲時間,也能夠傳props } else { return } } _isExpiration(expirationTime) { return expirationTime.getTime() - this.currentTime.getTime() > 500 } render() { const { animateName, animateChild } = this.state return ( <span className={'animated ' + animateName} style={{ display: 'block' }}> {animateChild} </span> ) } }
import React from 'react'; import styles from './index.less'; import Animate from '../components/index'; export default class AnimatedDemo extends React.Component { state = { show: false, } render() { const { show } = this.state return ( <div className={styles.Reading_activity}> <Animate enterClass='slideInRight' leaveClass='bounceOutRight'> {show ? <div className={styles.site__title + ' ' + styles.mega}>Animate.css</div> : null} </Animate> <button onClick={()=>{this.setState({show: false})}}>消失</button> <button onClick={()=>{this.setState({show: true})}}>出現</button> </div> ) } }
就到這裏,下期見css3