實作過場動畫 - React Transition Group + animate.css

React 過場動畫實作。CSS animation, React.v17

引言

製作過場動畫提昇UX。

React 動畫方案很多。複雜又炫麗的動畫相對的碼量也很驚人。然而我們要的不多只要簡簡單單的過場即可。經研究數天,發現結合 React Transition Grouparrow-up-rightanimate.cssarrow-up-right 就能滿足我們的需求。

關鍵源碼紀錄

案例:單一物件過場動畫

使用 CSSTransition 元件搭配 css animation class。 顯示(mount)與移除(unmount)加入過場動畫。

AppForm.tsx
import { Container, } from '@mui/material'
import { Paper } from '@mui/material'
import { H3, H4, AButton } from 'components/highorder'
import { useState, useReducer } from 'react'
// CSS
import { CSSTransition } from "react-transition-group";
import 'animate.css';

export default (props) => {
    const [show, toggleShow] = useReducer(f => !f, true)
    return (
    <Container>
        <H3>CSSTransition sample</H3>
        <AButton mutant='primary' label={`show:${show}`} onClick={toggleShow} />

        <CSSTransition
            in={show}
            timeout={300}
            classNames={{
                enter: "animate__animated",
                enterActive: "animate__fadeInUp",
                exit: "animate__animated",
                exitActive: "animate__fadeOutDown"
            }}
            unmountOnExit
        >
            <Paper sx={{ p: 4 }}>
                <H3>
                    一個動畫元素<br />
                    An animated element
                </H3>
            </Paper>
        </CSSTransition>

        <H4>EOF</H4>
    </Container >
    )
}

案例:多物件過場動畫,如:Todo List

使用TransitionGroupCSSTransition 元件搭配 css animation class。 新增與移除加入過場動畫。

EOF

Last updated