一个 TypeScript 版本的 Tag 组件示例:
tsx
interface Props extends React.HTMLAttributes<HTMLSpanElement> {tagType: "primary" | "secondary";text: string;}function Tag({ tagType, text, ...props }: Props) {const baseClasses = `inline-blockfont-sanstext-xspy-1.5px-3mb-4rounded-lg`;let classes = "";let backgroundColorClass = "";let textColorClass = "";switch (tagType) {case "primary":backgroundColorClass = "bg-primary-100 dark:bg-primary-500";textColorClass = "text-primary-500 dark:text-white";break;case "secondary":backgroundColorClass = "bg-secondary-100 dark:bg-secondary-500";textColorClass = "text-secondary-500 dark:text-white";break;default:// handle other possible typesbreak;}classes = `${baseClasses} ${backgroundColorClass} ${textColorClass}`;return (<span className={classes} {...props}>{text}</span>);}
声明 Props
接口来指定 Props
类型,通过扩展 React.HTMLAttributes<HTMLSpanElement>
来继承 span
HTML 元素的特性。最后,在属性中添加 {...props}
可以保持 JSX 中原有传递给 Tag
时的特性。