使用react 实现标签单选
import { styled,css } from 'styled-components';
import { Flex } from 'antd';
import React, { memo, useState } from 'react';
const TagWrap = styled.div`
margin-top: 16px;
`;
const CheckedCss = css`
background: #edf5ff;
border-radius: 6px;
color: rgba(0, 10, 26, 0.89);
`;
const Tag = styled.div<{ $checked?: boolean }>`
max-width: 90px;
overflow: hidden;
text-overflow: ellipsis;
font-size: 12px;
color: #616c77;
line-height: 16px;
padding: 4px 8px;
white-space: nowrap;
cursor: pointer;
margin-right: 8px;
${({ $checked }) => $checked && CheckedCss}
`;
interface propsType {
value: any;
mode?: 'multiple' | 'single';
onChange?: (value: any) => void;
dataSource?: any;
}
export const TagSelect = memo((props: propsType) => {
const { value, onChange, mode = 'single', dataSource } = props;
const [selectedTag, setSelectedTag] = useState<any>(value);
const handleChange = (value: any) => {
if (mode === 'multiple') {
const isChecked = selectedTag?.map((i: any) => i.key).includes(value.key);
const nextSelectedTags = isChecked
? selectedTag.filter((t: any) => t.key !== value.key)
: [...selectedTag, value];
setSelectedTag(nextSelectedTags);
onChange?.(nextSelectedTags);
} else {
// 禁止反选
if (value?.key === selectedTag) return false;
const val = selectedTag === value?.key ? undefined : value?.key;
setSelectedTag(val);
onChange?.(val);
}
};
const checked = (key: any) => {
if (mode === 'multiple') {
return selectedTag?.map((i: any) => i.key).includes(key);
}
return selectedTag === key;
};
return (
<TagWrap>
<Flex gap="8px 0" wrap="wrap" align="center">
{dataSource && dataSource.map((item: any) => {
return (
<Tag
key={item?.key}
$checked={checked(item?.key)}
onClick={() => handleChange(item)}
>
{item.value}
</Tag>
);
})}
</Flex>
</TagWrap>
);
});