原语 / Animate UI
Theme Toggler Button · Animate UI
循环切换主题的按钮,图标会转变成下一个。
安装
自有原语直接来自 @animate-ui/react,不依赖 Radix UI、Base UI 或 React Aria;装上包即可使用。
bun add @animate-ui/react motion
bunx shadcn@latest add @animate-ui/buttons-theme-toggler用法
直接从 @animate-ui/react 的对应子路径引入,下面就是完整示例;样式由你的类名决定。
import { useTheme } from 'next-themes';
import {
ThemeTogglerButton,
ThemeTogglerButtonIcon,
type Resolved,
type ThemeSelection,
} from '@/components/animate-ui/buttons/theme-toggler';
export function ThemeButton() {
const { theme, resolvedTheme, setTheme } = useTheme();
return (
<ThemeTogglerButton
theme={theme as ThemeSelection}
resolvedTheme={resolvedTheme as Resolved}
setTheme={setTheme}
modes={['light', 'dark']}
aria-label="Toggle theme"
>
<ThemeTogglerButtonIcon light={<SunIcon />} dark={<MoonIcon />} />
</ThemeTogglerButton>
);
}动效
- 旧图标旋转 90°、缩到一半并进入 2px 模糊后淡出,新图标从 90° 转回并长出,0.3s ease-out。
- 两个图标朝同一方向旋转;减少动效下直接换图标。
所有时长都会乘以 AnimateUIProvider 的 tempo,并遵守系统的减少动效设置。
API
动效相关的 transition 与 exitTransition 是 Animate UI 唯一新增的属性;其余 props 见上表。
| 属性 | 类型 | 默认值 |
|---|---|---|
| variant | 'default' | 'accent' | 'outline' | 'ghost' | null | 'default' |
| size | 'default' | 'sm' | 'lg' | null | 'default' |
| theme | 'light' | 'dark' | 'system' | — |
| resolvedTheme | 'light' | 'dark' | — |
| setTheme | (theme: 'light' | 'dark' | 'system') => void | — |
| modes | ('light' | 'dark' | 'system')[] | ['light', 'dark', 'system'] |
| hoverScale | number | 1 |
| tapScale | number | 0.97 |
| transition | Transition | { type: 'spring', stiffness: 550, damping: 30, restSpeed: 10 } |
| asChild | boolean | false |
| …props | HTMLMotionProps<'button'> | — |
| light | React.ReactNode | — |
| dark | React.ReactNode | — |
| system | React.ReactNode | — |
| rotate | number | 90 |
| transition | Transition | { duration: 0.3, ease: [0.23, 1, 0.32, 1] } |
| …props | React.ComponentProps<'span'> | — |
| data-theme | 'light' | 'dark' | 'system' | — |
未列出的属性与上游 API 完全一致,可在 官方文档 查阅。
内容对应官方文档 2026-10-18 版本。