一、安装并引入第三方库
npm install react-transition-group --save
复制代码
二、对一个元素开发动画
首先利用CSSTransition进行单个元素的动画开发。
//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;
}
复制代码
三、对一组元素进行动画操作
//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使用动画的新姿势,记录一下,希望对大家有帮助。