从零开始使用react写一个随机变色的标签组件

从零开始使用react写一个随机变色的标签组件

标签定义及引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
*
* color: 设置标签颜色
* visible: 标签是否显示 true
* closable: 标签是否可以关闭(点击默认关闭) false
* onClose: 关闭会调
* icon: Icon
*/
import React, {useState} from 'react';
import classnames from 'classnames';

interface IPropsTag {
color?: string;
visbile?: boolean;
closable?: boolean;
onClose?: () => void;
icon?: React.ReactNode;
children?: any
}

定义标签接口并且引入相关依赖

标签实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
export const Tag: React.FC<IPropsTag> = (props) => {

const {color, visbile = true, closable = false, onClose, icon} = props;

const [showTag, setShowTag] = useState(visbile);

const handleClose = () => {
onClose && onClose();
setShowTag(false);
};

return (
<div
className={classnames(tagStyles.OwnTag, color ? tagStyles.hasuserColor : '')}
style={{
display: !showTag ? 'none' : 'visible',
color: '#333333',
backgroundColor: color,
}}
>
{icon && <span style={{marginRight: 4}}>{icon}</span>}
<span className={tagStyles.TagTextOwn}>{props.children}</span>
{closable && (
<span className={tagStyles.closeBtn} onClick={handleClose}>
x
</span>
)}
</div>
);
};

实现标签组件

样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
.tagBox{
margin-bottom: 10px;
}

.OwnTag {
margin: 4px 16px 4px 0;
padding: 0 4px;
border-radius: 4px;
cursor: default;
display: inline-block;
font-size: 14px;
line-height: 20px;
white-space: nowrap;
background-color: #fafafa;
border: 1px solid #d9d9d9;
}
.hasuserColor {
color: #fff;
background-color: transparent;
}
.TagTextOwn {
font-weight: 600;
}
.closeBtnWhite {
margin-left: 4px;
color: rgba(255, 255, 255, 0.8);
cursor: pointer;
}
.closeBtn {
margin-left: 4px;
color: rgba(0, 0, 0, 0.8);
cursor: pointer;
}

标签使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export default function DefaultPostTags({tagstr}: { tagstr: string }) {
const tags = tagstr.split(",")
const colors = ["#cce7e0", "#dbdcf4", "#fcf4cc", "#fbd2d4"]

return (
<div className={tagStyles.tagBox}>
{
tags.map((tag) => {
const randomColor = colors[Math.floor(Math.random() * colors.length)];

return <Tag key={tag} color={randomColor} closable={false}>
{tag}
</Tag>
})
}
</div>
)
}

实际效果

作者

Terwer

发布于

2022-08-05

更新于

2022-08-05

许可协议

评论