324 - 《Framer Motion》

发布于 2023年7月20日

简单学习了下 Framer Motion,做下记录。之所以说简单学习,是因为我连官网文档都没看。。

1、Framer Motion 和 Framer 啥关系?Framer 是一个低代码网页生成工具,而 Framer Motion 是一个动画库。前者在部分产品中用了后者。Framer Motion 主要是为 React 设计的,其中部分功能也做了通用化处理,可以适用于原生 DOM。

2、Framer Motion 非常强大,同时也非常大。只用 import { motion } from 'framer-motion' 就会让你的产物多增加 97K 的产物尺寸(压缩后 gzip 前)。同时由于他用了一些高级特性比如 Proxy,使用时还需要注意浏览器兼容性,Framer 官网的浏览器兼容性是 Safari 13+、Chrome/Edge 81+ 和 Firefox 100+,还是比较高的。这些也决定了 Framer Motion 其实是有一定使用限制的。

3、Framer Motion 的学习门槛是比较陡的,里面包含大量的概念、配置项和动画类型,但不妨碍我们可以通过几个例子快速入门。

1)基础动画。

图。

import { motion } from 'framer-motion';
import React from 'react';
import { styled } from 'styled-components';

const SPRING = {
  type: 'spring',
  stiffness: 200,
  damping: 25,
};

const ToggleButtonWrapper = styled.div`
  padding: 20px 0;
  div {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: #ff02c4;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
`;

export function ToggleButton() {
  const [isEnabled, setIsEnabled] = React.useState(true);
  return (
    <ToggleButtonWrapper>
      <motion.div
        initial={false}
        transition={SPRING}
        animate={{
          x: isEnabled ? 0 : 100,
        }}
        onClick={() => {
          setIsEnabled(!isEnabled);
        }}
      >
        Toggle
      </motion.div>
    </ToggleButtonWrapper>
  );
}

我是基于 styled-components 写的样式,可切换成其他的。动画通过 motion.div 加配置项实现,比如通过 animate 设置动画属性,通过 transition 设置动画过程,通过把 initial 设置为 false 是禁用初始动画,可以防止初始渲染时闪一下。

补充一些背景知识。1)motion.div 基于 proxy,你甚至可以写 motion.abcde。基于此,motion 可以在 svg 里使用,2)为啥 <foo /> 需要遵循首字母大写原则,而 motion.div 却不需要遵守?因为首字母大写是为了和 html 标签不冲突,而对象访问形式比如 foo.bar 肯定不会冲突,所以不需要遵守这个原则。

2)Layout 动画。

一旦涉及到一些和布局相关的属性动画时,比如 position、flex 相关的 CSS 属性变化,animate 属性就无能为力了,需要切换的 Layout 动画模式。

import { motion } from 'framer-motion';
import React from 'react';
import { styled } from 'styled-components';

const LayoutButtonWrapper = styled.div`
  padding: 20px 0;
  button {
    /* 为了让文字动画平滑 */
    display: flex;
    justify-content: center;
    align-items: flex-start;

    backgr

内容预览已结束

此内容需要会员权限。请先登录以查看完整内容。