零经验学 react 的第15天 - 过渡动画(使用 react-transition-group 库进行实现)

一、安装依赖:react-transition-group

reactcommunity.org/react-trans...

bash 复制代码
npm install react-transition-group

二、过渡动画实现示例

jsx

jsx 复制代码
import { CSSTransition } from 'react-transition-group';
import React, { useRef } from 'react';
import './index.css';


function Transition1() {
    const [show, setShow] = React.useState(true);
    const timeout = 3000
    const nodeRef = useRef(null);
    
    return (
        <div>
            <h2>过渡动画</h2>
            <div className="btn-group" style={{ display: 'flex', gap: '10px', justifyContent: 'center', cursor: 'pointer' }}>
                <p onClick={() => setShow(true)} style={show ? { color: 'red' } : {}}>显示</p>
                <p onClick={() => setShow(false)} style={!show ? { color: 'red' } : {}}>隐藏</p>
            </div>


            {/*
                1、nodeRef方式使用CSSTransition:
                - 通过nodeRef属性传入ref对象,来避免findDOMNode的使用,从而避免在严格模式下出现警告。
                - 需要注意的是,使用nodeRef时,必须确保ref对象正确地引用了要应用过渡效果的DOM节点。
                - 另外,nodeRef方式不支持某些过渡效果,如appear效果。
            */}


            {/*
                2、classNames、in、timeout
                - classNames 属性指定了过渡效果的类名前缀,这些类名会在不同的过渡阶段自动添加到元素上,从而实现动画效果。
                - 通过 in 属性控制过渡效果的触发,当 in 为 true 时,元素进入过渡状态;当 in 为 false 时,元素离开过渡状态。
                - timeout 属性指定了过渡效果的持续时间,单位为毫秒。
            */}

            <CSSTransition nodeRef={nodeRef} classNames="div-box" in={show} timeout={timeout}>
                <div ref={nodeRef} className="div-box">
                <h3>内容</h3>
                </div>
            </CSSTransition>
        </div>
    );
}

export default Transition1;

css

css 复制代码
.div-box {
    transition: opacity 3s;
}

/* 显示 */
.div-box-enter {
    display: block;
    opacity: 0;
}

.div-box-enter-active {
    display: block;
    opacity: 0.5;
}

.div-box-enter-done {
    display: block;
    opacity: 1;
}


/* 隐藏 */
.div-box-exit {
    display: block;
    opacity: 1;
}

.div-box-exit-active {
    display: block;
    opacity: 0.5;
}

.div-box-exit-done {
    display: none;
    opacity: 0;
}
相关推荐
@大迁世界9 小时前
Firefox 本地模式:localhost 再见了 ?
前端·架构
米米商聊11 小时前
同名附件为什么被 Map 覆盖?重复键与一对多索引
前端·javascript
echome88812 小时前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌12 小时前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易12 小时前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
前端的日常13 小时前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师13 小时前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么13 小时前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒13 小时前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
hunter_07613 小时前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端