其它组件
必读指南
tag 完整案例
Tag 组件太简单了

前言
Tag 组件本身没有任何难度,就是一个简单的 div 加上一些样式。
源码如下:
1'use client';
2
3import { cs } from '@/_utils';
4import { IconCloseLine, IconLoadingLine, useMergeValue } from '@t-headless-ui/react';
5import { useState } from 'react';
6
7function isPromiseInstance(value: any): value is Promise<any> {
8 return value && value instanceof Promise;
9}
10export function TTag(props: {
11 children: React.ReactNode;
12 className?: string;
13 onClose?: (e: React.MouseEvent) => Promise<void> | void;
14 closable?: boolean;
15 visible?: boolean;
16}) {
17 const { children, className, onClose, closable, visible: visibleProp, ...rest } = props;
18 const [loading, setLoading] = useState(false);
19 const [visible, setVisible] = useMergeValue(true, {
20 value: visibleProp,
21 });
22
23 const handleOnClose = (e: React.MouseEvent) => {
24 const ret = onClose?.(e);
25 if (ret && isPromiseInstance(ret)) {
26 setLoading(true);
27 ret
28 .then(() => {
29 setLoading(false);
30 setVisible(false);
31 })
32 .catch(() => {
33 setLoading(false);
34 });
35 } else {
36 setVisible(false);
37 }
38 };
39
40 return (
41 <div
42 className={cs('inline-flex box-border items-center nowrap h-6 px-2 rounded-sm bg-color-100 text-[12px]', className, {
43 hidden: !visible,
44 })}
45 {...rest}
46 >
47 {children}
48 {closable && visible && !loading && (
49 <IconCloseLine onClick={handleOnClose} className="ml-1 cursor-pointer hover:text-color-400 duration-200 transition-colors" />
50 )}
51 {loading && <IconLoadingLine className="ml-1 animate-spin" />}
52 </div>
53 );
54}最后,欢迎加入到我们的组件库交流群中。有什么疑问都可以在群里讨论,并且会有视频直播每个组件的实现。
更重要的是,我可以帮助你增加一些简历中的核心项目,例如我们这个组件库级别的。无论你是面试初级开发还是到前端技术专家,都会帮助你在面试中脱颖而出。