一个 ts Tag 组件
React

一个 ts Tag 组件

一个 TypeScript 版本的 Tag 组件示例:声明 Props 接口来指定 Props 类型,通过扩展 React.HTMLAttributes\<HTMLSpanElement> 来继承 s...

花野猫

花野猫

更新于 2023-08-04

880

一个 TypeScript 版本的 Tag 组件示例:

tsx
interface Props extends React.HTMLAttributes<HTMLSpanElement> {
tagType: "primary" | "secondary";
text: string;
}
function Tag({ tagType, text, ...props }: Props) {
const baseClasses = `
inline-block
font-sans
text-xs
py-1.5
px-3
mb-4
rounded-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 types
break;
}
classes = `${baseClasses} ${backgroundColorClass} ${textColorClass}`;
return (
<span className={classes} {...props}>
{text}
</span>
);
}

声明 Props 接口来指定 Props 类型,通过扩展 React.HTMLAttributes<HTMLSpanElement> 来继承 span HTML 元素的特性。最后,在属性中添加 {...props} 可以保持 JSX 中原有传递给 Tag 时的特性。