跳至正文
获取 Pro
动效组件M.28

字符变形文本

FreeRegistry
components/linyi/morphing-text.tsx
motion
"use client";
 
import * as React from "react";
import { AnimatePresence, motion } from "motion/react";
import { cn } from "@/lib/cn";
import { SPRING_SNAPPY } from "@/lib/motion";
 
export interface MorphingTextProps {
text: string;
className?: string;
}
 
export function MorphingText({ text, className }: MorphingTextProps) {
const uid = React.useId().replace(/:/g, "");
 
const characters = React.useMemo(() => {
const counts: Record<string, number> = {};
return Array.from(text).map((char) => {
const lower = char.toLowerCase();
counts[lower] = (counts[lower] ?? 0) + 1;
return {
id: `${uid}-${lower}-${counts[lower]}`,
label: char === " " ? "\u00A0" : char,
};
});
}, [text, uid]);
 
return (
<span
className={cn("inline-flex items-baseline whitespace-pre", className)}
aria-label={text}
>
<AnimatePresence mode="popLayout" initial={false}>
{characters.map((ch) => (
<motion.span
key={ch.id}
layoutId={ch.id}
initial={{ opacity: 0, y: 6, scale: 0.85 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -6, scale: 0.85 }}
transition={SPRING_SNAPPY}
aria-hidden="true"
className="inline-block"
>
{ch.label}
</motion.span>
))}
</AnimatePresence>
</span>
);
}