Communitygithub.com

AutoAnimate(@formkit/auto-animate)

为零配置 React 动画而生。适用于列表过渡、手风琴、提示框,或解决 SSR 错误与动画库复杂度问题。

auto-animate) 是什么?

AutoAnimate 是一个轻量级(3.28 KB gzip)、零依赖的动画库,支持 React、Vue、Svelte 及原生 JavaScript。它通过 `useAutoAnimate` Hook 让开发者只需将 ref 附加到父元素即可自动为列表的添加、移除和重排添加平滑动画。本技能不仅提供快速入门指南(2 分钟内可完成设置),还全面预防了 10 个以上已知问题,包括 SSR/Next.js 导入错误、条件渲染父元素、缺少唯一 key、Flexbox 宽度异常以及 Jest 测试报错等。此外,技能内置了 Cloudflare Workers 兼容性方案、SSR 安全模式、无障碍访问(遵循 `prefers-reduced-motion`)以及完整模板与脚本资源。开发者可根据场景在 AutoAnimate 与 Motion 之间做出最佳选择,并通过详细的检查清单确保实现正确。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/secondsky/claude-skills/auto-animate

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

AutoAnimate

状态:生产就绪 ✅
最后更新:2025-11-07
依赖:无(适用于任何 React 设置)
最新版本:@formkit/[email protected]


快速入门(2 分钟)

1. 安装 AutoAnimate

bun add @formkit/auto-animate

为什么这很重要:

  • 仅 3.28 KB gzip(Motion 为 22 KB)
  • 零依赖
  • 框架无关(React、Vue、Svelte、原生 JavaScript)

2. 添加到你的组件

import { useAutoAnimate } from "@formkit/auto-animate/react";

export function MyList() {
  const [parent] = useAutoAnimate(); // 1. 获取 ref

  return (
    <ul ref={parent}> {/* 2. 附加到父元素 */}
      {items.map(item => (
        <li key={item.id}>{item.text}</li> {/* 3. 就这样! */}
      ))}
    </ul>
  );
}

重要事项:

  • ✅ 始终为列表项使用唯一稳定的 key
  • ✅ 父元素必须始终渲染(不能是条件性的)
  • ✅ AutoAnimate 自动遵循 prefers-reduced-motion
  • ✅ 支持添加、移除和重排操作

3. 在生产环境使用(SSR 安全)

适用于 Cloudflare Workers 或 Next.js:

// 使用仅客户端导入以防止 SSR 错误
import { useState, useEffect } from "react";

export function useAutoAnimateSafe<T extends HTMLElement>() {
  const [parent, setParent] = useState<T | null>(null);

  useEffect(() => {
    if (typeof window !== "undefined" && parent) {
      import("@formkit/auto-animate").then(({ default: autoAnimate }) => {
        autoAnimate(parent);
      });
    }
  }, [parent]);

  return [parent, setParent] as const;
}

已知问题预防

本技能可预防 10 个以上 已知问题:

问题 #1:SSR/Next.js 导入错误

错误:"Can't import the named export 'useEffect' from non EcmaScript module"
来源:https://github.com/formkit/auto-animate/issues/55
原因:AutoAnimate 使用了服务器上不可用的 DOM API
预防措施:使用动态导入(参见 templates/vite-ssr-safe.tsx)

问题 #2:条件性父元素渲染

错误:当父元素是条件性时动画不生效
来源:https://github.com/formkit/auto-animate/issues/8
原因:ref 无法附加到不存在的元素
预防措施:

// ❌ 错误
{showList && <ul ref={parent}>...</ul>}

// ✅ 正确
<ul ref={parent}>{showList && items.map(...)}</ul>

问题 #3:缺少唯一 Key

错误:列表项动画不正确或闪烁
来源:官方文档
原因:React 无法追踪哪些项发生了改变
预防措施:始终使用唯一稳定的 key(key={item.id})

问题 #4:Flexbox 宽度问题

错误:元素在宽度上跳跃而非平滑动画
来源:官方文档
原因:flex-grow: 1 会等待周围内容
预防措施:对动画元素使用显式宽度而非 flex-grow

问题 #5:表格行显示问题

错误:移除行时表格结构被破坏
来源:https://github.com/formkit/auto-animate/issues/7
原因:display: table-row 与动画冲突
预防措施:对 <tbody> 应用动画而非单独的行,或使用基于 div 的布局

问题 #6:Jest 测试错误

错误:"Cannot find module '@formkit/auto-animate/react'"
来源:https://github.com/formkit/auto-animate/issues/29
原因:Jest 未能正确解析 ESM 导出
预防措施:在 jest.config.js 中配置 moduleNameMapper

问题 #7:esbuild 兼容性

错误:"Path '.' not exported by package"
来源:https://github.com/formkit/auto-animate/issues/36
原因:ESM/CommonJS 条件不匹配
预防措施:配置 esbuild 以正确处理 ESM 模块

问题 #8:CSS 位置副作用

错误:添加 AutoAnimate 后布局被破坏
来源:官方文档
原因:父元素自动获得 position: relative
预防措施:在 CSS 中考虑位置变化或显式设置

问题 #9:Vue/Nuxt 注册错误

错误:"Failed to resolve directive: auto-animate"
来源:https://github.com/formkit/auto-animate/issues/43
原因:插件未正确注册
预防措施:在 Vue/Nuxt 配置中正确设置插件(参见 references/)

问题 #10:Angular ESM 问题

错误:构建失败,提示 "ESM-only package"
来源:https://github.com/formkit/auto-animate/issues/72
原因:CommonJS 构建环境
预防措施:为 Angular 包格式配置 ng-packagr


何时使用 AutoAnimate vs Motion

使用 AutoAnimate 的场景:

  • ✅ 简单的列表过渡(添加/移除/排序)
  • ✅ 手风琴展开/折叠
  • ✅ 提示通知淡入/淡出
  • ✅ 表单验证消息出现/消失
  • ✅ 优先使用零配置
  • ✅ 小包体积至关重要(3.28 KB)
  • ✅ 应用于现有/第三方代码
  • ✅ 接受“足够好”的动画

使用 Motion 的场景:

  • ✅ 复杂的编排动画
  • ✅ 手势控制(拖拽、滑动、悬停)
  • ✅ 基于滚动的动画
  • ✅ 弹簧物理动画
  • ✅ SVG 路径动画
  • ✅ 需要关键帧控制
  • ✅ 动画变体/编排
  • ✅ 自定义缓动曲线

经验法则:90% 的情况使用 AutoAnimate,主体/交互动画使用 Motion。


关键规则

始终遵循

✅ 使用唯一稳定的 key - key={item.id} 而非 key={index}
✅ 保持父元素在 DOM 中 - 父元素 ref 始终渲染
✅ SSR 下仅客户端 - 对服务器环境使用动态导入
✅ 尊重可访问性 - 保持 disrespectUserMotionPreference: false
✅ 禁用动画测试 - 确保 UI 在没有动画时正常工作
✅ 使用显式宽度 - 避免在动画元素上使用 flex-grow
✅ 对表格应用 tbody - 而非单独的行

绝不这样做

❌ 条件性父元素 - {show && <ul ref={parent}>}
❌ 索引作为 key - key={index} 会破坏动画
❌ 忽略 SSR - 会在 Cloudflare Workers/Next.js 中出错
❌ 强制动画 - disrespectUserMotionPreference: true 破坏可访问性
❌ 直接动画化表格 - 使用 tbody 或基于 div 的布局
❌ 跳过唯一 key - 动画需要唯一 key
❌ 复杂动画 - 改用 Motion


配置

AutoAnimate 默认零配置。可选自定义:

import { useAutoAnimate } from "@formkit/auto-animate/react";

const [parent] = useAutoAnimate({
  duration: 250, // 毫秒(默认:250)
  easing: "ease-in-out", // CSS 缓动(默认:"ease-in-out")
  // disrespectUserMotionPreference: false, // 保持 false!
});

建议:除非有特殊设计要求,否则使用默认值。


使用捆绑资源

模板(templates/)

可复制粘贴的示例:

  • react-basic.tsx - 带添加/移除/重排的简单列表
  • react-typescript.tsx - 带类型和自定义配置的设置
  • filter-sort-list.tsx - 动画化的过滤和排序
  • accordion.tsx - 可展开部分
  • toast-notifications.tsx - 淡入/淡出消息
  • form-validation.tsx - 错误消息动画
  • vite-ssr-safe.tsx - Cloudflare Workers/SSR 模式

参考文档(references/)

  • auto-animate-vs-motion.md - 选择使用哪个的决策指南
  • css-conflicts.md - Flexbox、表格和位置陷阱
  • ssr-patterns.md - Next.js、Nuxt、Workers 的变通方案

脚本(scripts/)

  • init-auto-animate.sh - 自动化设置脚本

Cloudflare Workers 兼容性

AutoAnimate 与 Cloudflare Workers 静态资产完美兼容:

✅ 仅客户端 - 在浏览器中运行,不在 Worker 运行时
✅ 无 Node.js 依赖 - 纯浏览器代码
✅ 边缘友好 - 3.28 KB gzip
✅ SSR 安全 - 使用动态导入(参见 templates/)

Vite 配置:

export default defineConfig({
  plugins: [react(), cloudflare()],
  ssr: {
    external: ["@formkit/auto-animate"],
  },
});

可访问性

AutoAnimate 自动遵循 prefers-reduced-motion:

/* 用户的系统偏好 */
@media (prefers-reduced-motion: reduce) {
  /* AutoAnimate 自动禁用动画 */
}

重要:切勿设置 disrespectUserMotionPreference: true - 这破坏了可访问性。


官方文档


包版本(2025-11-07 已验证)

{
  "dependencies": {
    "@formkit/auto-animate": "^0.9.0"
  },
  "devDependencies": {
    "react": "^19.2.0",
    "vite": "^6.0.0"
  }
}

生产示例

本技能基于生产测试:

  • 包体积:3.28 KB gzip
  • 设置时间:2 分钟(Motion 需 15 分钟)
  • 错误:0(所有 10 个已知问题均已预防)
  • 验证:✅ 适用于 Vite、Tailwind v4、Cloudflare Workers、React 19

已测试场景:

  • ✅ 过滤/排序列表
  • ✅ 手风琴组件
  • ✅ 提示通知
  • ✅ 表单验证消息
  • ✅ SSR/Cloudflare Workers
  • ✅ 可访问性(prefers-reduced-motion)

故障排除

问题:动画不工作

解决方案:检查这些常见问题:

  1. 父元素是否始终在 DOM 中?(非条件性)
  2. 列表项是否具有唯一稳定的 key?
  3. ref 是否附加到动画子元素的直接父元素?

问题:SSR/Next.js 错误

解决方案:使用动态导入:

useEffect(() => {
  if (typeof window !== "undefined") {
    import("@formkit/auto-animate").then(({ default: autoAnimate }) => {
      autoAnimate(parent);
    });
  }
}, [parent]);

问题:列表项闪烁而非动画

解决方案:添加唯一 key:key={item.id} 而非 key={index}

问题:Flexbox 宽度问题

解决方案:使用显式宽度而非 flex-grow: 1

问题:表格行无法动画

解决方案:将 ref 应用到 <tbody>,而非单独 <tr> 元素


完整设置检查清单

  • 已安装 @formkit/[email protected]
  • 使用 React 19+(或 Vue/Svelte)
  • 已将 ref 添加到父元素
  • 父元素始终渲染(非条件性)
  • 列表项具有唯一稳定的 key
  • 已测试 prefers-reduced-motion
  • 如果使用 Cloudflare Workers/Next.js,已实现 SSR 安全
  • 没有 Flexbox 宽度问题
  • 开发服务器运行无错误
  • 生产构建成功

有疑问?遇到问题?

  1. 查看 templates/ 获取工作示例
  2. 查看 references/auto-animate-vs-motion.md 了解库对比
  3. 查看 references/ssr-patterns.md 了解 SSR 变通方案
  4. 查看官方文档:https://auto-animate.formkit.com
  5. 查看 GitHub issues:https://github.com/formkit/auto-animate/issues

生产就绪? ✅ 是 - 13.6k 星,积极维护,零依赖。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能