
正文
react中使用react-transition-group实现动画
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
css动画的方式,比较局限,涉及到一些js动画的时候没法处理了。react-transition-group是react的第三方模块,借住这个模块可以更方便的实现更加复杂的动画效果
https://github.com/reactjs/react-transition-group
https://reactcommunity.org/react-transition-group/css-transition
主要用里面的cssTransition
js
import React, { Component, Fragment } from 'react';
import { CSSTransition } from 'react-transition-group';
import './style.css'class App extends Component {
constructor(props){
super(props);
this.state = {
show: true
}
this.handleToggle = this.handleToggle.bind(this);
}render() {
return (
<Fragment>
<CSSTransition
in={this.state.show}
timeout={}
classNames="fade"
unmountOnExit
appear={true}
>
<div>hello</div>
</CSSTransition>
<button onClick={this.handleToggle}>toggle</button>
</Fragment>
)
}handleToggle() {
this.setState({
show: this.state.show ? false : true
})
}
}
export default App;
css
/* 入场动画 fade-appear fade-appear-active 第一次才游泳*/
.fade-enter, .fade-appear{
opacity:;
}
.fade-enter-active, .fade-appear-active{
opacity:;
transition: opacity 1s ease-in;
}
.fade-enter-done{
opacity:;
}/* 出场动画 */
.fade-exit{
opacity:;
}
.fade-exit-active{
opacity:;
transition: opacity 1s ease-in;
}
.fade-exit-done{
opacity:;
}
咋一看,这个实现过程反而变得复杂了,并没有变得简单,虽然复杂了,但是带给了我们很多新的特性。
看官方网站,他接受一个unmountOnExit这样一个属性,发现dom也别移除了,这个功能之前是没法做到的,用这个库就显得非常简单。
再看,后面提供了很多的钩子函数,这就可以通过js额外的干一点事情,比如hello显示出来之后,希望他的颜色变成红色,
.fade-enter-done{
opacity:;
color: red;
}
这样就可以了。但是也可以用 js实现这个动画,在css属性上加上
onEntered={(el)=>{
el.style.color='blue'
}}
这种语法在之前做动画的时候也是没法实现的
多个动画的js
import React, { Component, Fragment } from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import './style.css'
class App extends Component {
constructor(props){
super(props);
this.state = {
list: []
}
this.handleAddItem = this.handleAddItem.bind(this);
} render() {
return (
<Fragment>
<TransitionGroup>
{
this.state.list.map((item, index)=>{
return (
<CSSTransition
timeout={}
classNames="fade"
unmountOnExit
appear={true}
>
<div key={index}>{item}</div>
</CSSTransition>
)
})
}
</TransitionGroup>
<button onClick={this.handleAddItem}>toggle</button>
</Fragment>
)
} handleAddItem() {
this.setState((prevState) => {
return {
list: [...prevState.list, 'item']
}
})
}
}
export default App;






![【电子书】[职业技术] 《深入react技术栈》[陈屹][epub+mobi+azw3] 【电子书】[职业技术] 《深入react技术栈》[陈屹][epub+mobi+azw3]](https://www.04ip.com/template/qe/style/noimg/10.jpg)
