react动画的两种写法

1、用原生的css来写

Animation.js

import React, { Component, Fragment } from 'react';
import './Animation.css'
class Animation extends Component {
    constructor(props) {
        super(props)
        this.state = {
            show: true
        }
        this.divControl = this.divControl.bind(this)
    }
    divControl = () => {
        this.setState(() => ({ show: this.state.show ? false : true }))
    }
    render() {
        return (
            <Fragment>
                <div className={this.state.show ? 'show' : 'hide'}>hello</div> 
                <button onClick={this.divControl}>按钮</button>
                {/* 点击按钮hello展示或隐藏 */}
            </Fragment>
        );
    }
}
export default Animation;

Animation.css

/* 过度效果 */
.show{
    /* opacity: 1;
    transition: all 1s; */
    animation: show-item 2s ease-in forwards;
}
.hide{
    /* opacity: 0;
    transition: all 1s; */
    animation: hide-item 2s ease-in forwards;
    /* forwards 能够保存动画最后一帧的样式 必写 */
}
/* 动画效果 */
@keyframes hide-item{
    0%{
        opacity: 1;
        color: red;
    }
    50%{
        opacity: 0.5;
        color: green;
    }
    100%{
        opacity: 0;
        color: blue;
    }
}

@keyframes show-item{
    0%{
        opacity: 0;
        color: red;
    }
    50%{
        opacity: 0.5;
        color: green;
    }
    100%{
        opacity: 1;
        color: blue;
    }
}

2、用react-transition-group的CSSTransition来写

Animation.js

import React, { Component, Fragment } from 'react';
import { CSSTransition } from 'react-transition-group';
import './Animation.css'
class Animation extends Component {
    constructor(props) {
        super(props)
        this.state = {
            show: true
        }
        this.divControl = this.divControl.bind(this)
    }
    divControl = () => {
        this.setState(() => ({ show: this.state.show ? false : true }))
    }
    render() {
        return (
            <Fragment>
                {/* 使用react-transition-group中的CSSTransition */}
                <CSSTransition
                    in={this.state.show}
                    timeout={1000}
                    classNames='fade'
                    unmountOnExit
                    onEntered={(el)=>{el.style.color='blue'}}
                    appear={true}
                >
                    <div>hello</div>
                </CSSTransition>
                {/* CSSTransition会自动往里面div加一些样式,
                    in来控制动画的执行,
                    timeout是动画时间 
                    unmountOnExit可以当动画执行完溢出dom
                    onEntered 入场动画执行完之后的钩子
                    appear 页面刷新就来一次动画效果
                    */}

                <button onClick={this.divControl}>按钮</button>
                {/* 点击按钮hello展示或隐藏 */}
            </Fragment>
        );
    }
}
export default Animation;

猜你喜欢

转载自blog.csdn.net/weixin_44745920/article/details/109591520