react标签单选组件

使用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>
  );
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值