基础模板
import React, { Component } from 'react';
class Boss extends Component {
constructor(props) {
super(props);
this.state = {
isShow:true
}
this.toToggole=this.toToggole.bind(this)
}
render() {
return (
<div>
<div className={this.state.isShow? 'show':'hide'}>
用CSS3实现react 动画
</div>
<div>
<button onClick={this.toToggole}>点击</button>
</div>
</div>
);
}
toToggole() {
this.setState({
isShow:this.state.isShow?false:true
})
}
}
export default Boss;
初级:
.show{
opacity: 1;
transition: all 1.5s ease-in;
}
.hide{
opacity: 0;
transition: all 1.5s ease-in;
}
中级:
Css3中的帧动画
.show{
animation: show-item 2s ease-in forwards;
}
.hide{
animation: hide-item 2s ease-in forwards;
}
@keyframes show-item{
0%{
opacity: 0;
color: yellow;
}
50%{
opacity: 0.5;
color: red;
}
100%{
opacity: 1;
color: green;
}
}
@keyframes hide-item{
0%{
opacity: 1;
color: yellow;
}
50%{
opacity: 0.5;
color: red;
}
100%{
opacity: 0;
color: green;
}
}
高级
这次用react-transition-group做一个togglebutton控制div显示和隐藏的例子,首先我们需要安装react-transition-group,输入
react-transition-group 动画库
npm install react-transition-group
组件中引入CSSTransition模块:
import {CSSTransition} from 'react-transition-group'
render() {
return (
<div>
<CSSTransition
in={this.state.isShow} // 如果this.state.isShow从false变为true,则动画入场,反之out出场
timeout={2000} //动画执行2秒
classNames="boss-text" //自定义的class名
unmountOnExit //可选,当动画出场后在页面上移除包裹的dom节点
>
<div >用CSS3实现react 动画</div>
</CSSTransition>
<div>
<button onClick={this.toToggole}>点击</button>
</div>
</div>
);
}
一旦动画入场,插件将会自动的在包裹住的标签上添加很多css样式,默认class名是boss-text,所以我们需要给CSSTransition标签加上classNames='boss-text',然后去css文件进行配置:
/* 入场之前 */
//enter是入场前的刹那(点击按钮)
.boss-text-enter{
opacity: 0;
}
//指入场后到入场结束的过程
.boss-text-enter-active{
opacity: 1;
transition: opacity 2000ms;
}
//入场动画执行完毕后,保持状态
.boss-text-done{
opacity: 1;
}
/* 出场 */
.boss-text-exit{
opacity: 1;
}
.boss-text-exit-active{
opacity: 0;
transition: opacity 2000ms;
}
.boss-text-done{
opacity: 0;
}
如果页面上一组dom都需要添加动画效果时我们需要在最外面再加一个TransitionGroup
import React, { Component } from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group'
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={1000}
classNames='fade'
unmountOnExit
appear={true}
key={index}
>
<div>{item}循环列表中的内容</div>
</CSSTransition>
)
})
}
</TransitionGroup>
<button onClick={this.handleAddItem}>toggle</button>
</div>
)
}
}
export default App;
网友评论