TransitionGroup 的作用,博主用通俗易懂的话来讲就是一个一组元素添加动画,在我们的实际开发当中有时可能会有这么一个需求就是,在一个页面上,有添加和删除,在做这些操作的时候需要都带上动画,那么这个时候就可以使用 TransitionGroup 来快速实现。
案例
App.js:
import React from 'react';
import './App.css'
import {CSSTransition, TransitionGroup} from 'react-transition-group';class App extends React.Component {constructor(props) {super(props);this.state = {heroList: [{id: 1, name: '鲁班'},{id: 2, name: '虞姬'},{id: 3, name: '黄忠'},]}}render() {return (<div><ul><TransitionGroup>{this.state.heroList.map((obj, index) => {return (<CSSTransition key={obj.id}timeout={3000}classNames={'item'}><lionClick={() => {this.removeHero(index)}}>{obj.name}</li></CSSTransition>)})}</TransitionGroup></ul><buttononClick={() => {this.btnClick()}}>新增</button></div>);}btnClick() {this.setState({heroList: [...this.state.heroList, {id: this.state.heroList.length + 1, name: '阿珂'}]})}removeHero(index) {const list = this.state.heroList.filter((idx) => {return idx !== index;})this.setState({heroList: list})}
}export default App;
App.css:
.item-enter {/*进入动画执行之前绑定的类名*/opacity: 0;transform: translateX(100%);
}.item-enter-active {/*进入动画执行过程中绑定的类名*/opacity: 1;transform: translateX(0);transition: all 3s;
}.item-enter-done {/*进入动画执行完毕之后绑定的类名*/
}.item-exit {/*退出动画执行之前绑定的类名*/opacity: 1;transform: translateX(0);
}.item-exit-active {/*退出动画执行过程中绑定的类名*/opacity: 0;transform: translateX(100%);transition: all 3s;
}.item-exit-done {/*退出动画执行完毕之后绑定的类名*/
}
注意点
- 在企业开发中一定要保证
CSSTransition key
的唯一性,否则动画会失效 - TransitionGroup 与 CSSTransition 是紧贴的,中间不能包含其它元素,否则动画则不会生效