跳到正文
目录与搜索
⌘K

原语 / Animate UI

Code Block · Animate UI

使用 Shiki 高亮的代码块,可以按字符逐字打出代码,并自动跟随最后一行滚动。

安装

自有原语直接来自 @animate-ui/react,不依赖 Radix UI、Base UI 或 React Aria;装上包即可使用。

终端
bun add @animate-ui/react motion
bunx shadcn@latest add @animate-ui/components-code-block

用法

直接从 @animate-ui/react 的对应子路径引入,下面就是完整示例;样式由你的类名决定。

code-block.tsx
import { CodeBlock } from '@animate-ui/react/primitives/code-block';

export function Snippet() {
  return (
    <CodeBlock
      code="console.log('Hello, world!');"
      lang="javascript"
      writing
      duration={2000}
    />
  );
}

动效

  • writing 开启后,代码在 delay 之后按 duration 均匀逐字出现。
  • 代码块与 scrollContainerRef 平滑滚动,始终跟住最后一行;减少动效下直接显示完整代码。

所有时长都会乘以 AnimateUIProvider 的 tempo,并遵守系统的减少动效设置。

API

动效相关的 transition 与 exitTransition 是 Animate UI 唯一新增的属性;其余 props 见上表。

属性类型默认值
cursorbooleantrue
copyButtonbooleantrue
scrollClassNamestring—
codestring—
langstring—
theme"light" | "dark""light"
themes{ light: string; dark: string }{ light: "github-light", dark: "github-dark" }
writingbooleanfalse
durationnumber5000
delaynumber0
onDone() => void—
onWrite(info: { index: number; length: number; done: boolean }) => void—
scrollContainerRefReact.RefObject<HTMLElement | null>—
inViewbooleanfalse
inViewMarginstring"0px"
inViewOncebooleantrue
…propsReact.ComponentProps<'div'>—

未列出的属性与上游 API 完全一致,可在 官方文档 查阅。

内容对应官方文档 2026-10-18 版本。