前言 #
在 Day 10 我們認識了 Code 元件,主要用於呈現程式碼的動畫效果。今天要介紹的元件與其概念相似,不過有所不同 —— Code Block。它是一個不帶樣式的動畫基礎元件,能夠讓你自由發揮,依照需求去打造專屬風格。在 Animate UI Docs 中,它被歸類於 Primitives 元件。
Code Block #

-
使用 Shadcn CLI 加入 Code Block
npx shadcn@latest add @animate-ui/primitives-animate-code-block -
Import 元件並將元件放在想要的位置上
不同的程式碼段落可以依照
const CODESKey-Value 分類import { CodeTabs } from '@/components/animate-ui/components/animate/code-tabs'; const CODES = { first: `Your Code Here` }; <CodeBlock code={CODES.first} lang="tsx" theme={'light'} writing={true} />需留意 Import 來源不同,兩者同樣名為
<CodeBlock>但程式內部還是有些許差異。 -
若還有想要微調,可以增加更多參數 (? 表示為選填參數)
參數 參數型態 說明 code string程式碼內容 lang string程式語言標籤,例如 js、ts、bash等theme 'light' | 'dark'指定顯示主題模式,僅限 light或dark。themes { light: string; dark: string }自訂主題樣式,分別對應淺色與深色模式。預設為 { light: "github-light", dark: "github-dark" }writing boolean是否啟用「打字機效果」來逐字顯示程式碼 duration number打字機效果持續時間(毫秒 ms) delay number動畫開始前延遲時間(毫秒 ms) onDone () => void當打字效果完成後觸發的回調函式 onWrite (info: { index: number; length: number; done: boolean }) => void打字過程中遞迴 Function,回傳目前字元索引、總長度、是否完成 UseIsInViewOptions { root?: Element | null; rootMargin?: string; threshold?: number | number[] }控制元素進入 viewport 的條件
小結 #
在今天的文章中,我們探索 Animate UI Code Block 的使用方式。這個元件本身沒有設計修飾,卻能成為展現個人風格的最佳基礎。接下來,明天我們會延伸到 Animate UI Cursor 元件,示範如何讓元件與使用者游標互動,帶來更多動態效果。