Skip to content
  • 混合引擎:享受浏览器动画的硬件加速,又结合Js的灵活性

我的云端playground:link

官方文档:http://motion.dev/docs/react-animation

安装

powershell
npm install motion

导入

tsx
// React
import { motion } from "motion/react"

// React Server Components
import * as motion from "motion/react-client"

基础使用

motion组件

motion组件,例如<motion.div />,就是普通的组件,只不过增加了动画能力。

animate属性

当animate初始化和发生改变时,动画会执行。

tsx
import * as motion from "motion/react-client"

export default function Rotate() {
    return (
        <motion.div
            style={box}
            animate={{ rotate: 360 }}
            transition={{ duration: 1 }}
        />
    )
}

/**
 * ==============   Styles   ================
 */

const box: React.CSSProperties = {
    width: 100,
    height: 100,
    backgroundColor: "#ff0088",
    borderRadius: 5,
}

transition.duration

animate的执行时间,如果animate中也定义了,以内部的时间为准(单位秒),比如下面就是以3s,不指定也是有默认值的。

tsx
animate={
  {
    rotate: 260,
    translateX: 100,
    transition: {
      duration: 3
    }
  }
}
transition={
  {
    duration: 0.8
  }
}

initial属性

只是初始化

tsx
<motion.button style={box} initial={{ scale: 0 }} animate={{ scale: 1 }} />

Gestures交互姿势

支持hover, tap, focus, drag.

tsx
<motion.button
  whileHover={{ scale: 1.1 }}
  whileTap={{ scale: 0.95 }}
  onHoverStart={() => console.log('hover started!')}
/>

滚动条互动

进入可视区域后变色

tsx
<motion.div
  initial={{ backgroundColor: "rgb(0, 255, 0)", opacity: 0 }}
  whileInView={{ backgroundColor: "rgb(255, 0, 0)", opacity: 1 }}
/>

横向进度条

tsx
const { scrollYProgress } = useScroll()

return <motion.div style={{ scaleX: scrollYProgress }} />

Layout

AnimatePresence,exit

tsx
<AnimatePresence>
  {show ? <motion.div key="box" exit={{ opacity: 0 }} /> : null}
</AnimatePresence>