爱意满满的作品展示区。
deepkolos

80 行代码实现 Preact-Transition 组件

  •  
  •   deepkolos ·
    deepkolos · May 8, 2020 · 2115 views
    This topic created in 2232 days ago, the information mentioned may be changed or developed.

    Preact 是 3kb 轻量化方案, 但是一些基础组件找起来比较困难, 用起来也比较别扭,其中一个就是 Transition 组件, 尝试过preact-transition-group, 但是直接 npm 安装使用就报错了...因为有 preact 版本兼容问题

    看了下源码

    transition.js

            // 这一行代码没兼容, 新版 preact children 不一定是都是数组
    359 -	const child = children[0]
        +	const child = children[0] || children 
    360     return cloneElement(child, childProps)
    

    但是看了 transition.js (391 行) + CSSTransition(181 行), 感觉不需要这么多行代码即可实现所需的 Transition 组件

    之前也写过弹窗过渡动画的组件, 也熟悉其生命周期, 所以简单梳理下状态变换流程就可以编写了

    状态扭转也两个分支:
    enter->entering->entered
    exit->exiting->exited
    
    而其中 4 个状态的流转可以由两个变量派生出来:show 和 switching
    enter/entered/exit/exited
    
    而 entering 则紧跟着 enter, exiting 则紧跟着 exit
    
    状态的对应关系:
    show && !switching => entered
    !show && !switching => exited
    show && switching => enter
    !show && switching => exit
    
    剩下就是加上 show 变化对 switching 的变化即可
    

    最终写下来只需要 80 行代码即可实现了

    1. 接口与 CSSTransition 类似
    2. 大概 80 行代码
    3. 无需设置 duration, duration 与 transition-duration 一样
    4. 无需繁琐设置 classNames 传递一个 className 即可, css 里配合 data-state 来命中状态

    使用 Preact 的同学可以尝试下, 简约框架搭配简约组件

    这里可以体验DEMO

    https://github.com/deepkolos/pc-transition

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2623 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 12:59 · PVG 20:59 · LAX 05:59 · JFK 08:59
    ♥ Do have faith in what you're doing.