Concis组件库封装——Badge徽标

1,091 阅读1分钟

您好,如果喜欢我的文章,可以关注我的公众号「量子前端」,将不定期关注推送前端好文~

徽标其实和上文的Avatar头像是配套的,通常徽标的需求都是在头像的基础上提供的,因此本文将介绍徽标组件的封装,徽标其实是一个展示类组件,并没有什么交互,因此这个组件实现起来比较简单~

先看一下组件库的文档吧~

在这里插入图片描述 在这里插入图片描述

组件的API能力如下:

在这里插入图片描述

组件的源码如下:

import React, { FC, memo, useMemo } from 'react';
import { badgeProps } from './interface';
import './index.module.less';

const Badge: FC<badgeProps> = (props) => {
  const {
    children,
    style = {},
    count,
    maxCount = 99,
    dotStyle = {},
    dot,
    offset = [2, 2],
    text,
  } = props;
  console.log(children);

  const computedCount = useMemo(() => {
    if (count) {
      if (maxCount) {
        if (count > maxCount) {
          return `${maxCount}+`;
        } else {
          return count;
        }
      } else {
        return count;
      }
    }
  }, [count, maxCount]);
  const countStyle = useMemo(() => {
    if (children) {
      if (String(computedCount).length > 1) {
        return {
          borderRadius: '20px',
        };
      } else {
        return {
          borderRadius: '50%',
        };
      }
    } else {
      if (String(computedCount).length == 1) {
        return {
          padding: '',
        };
      } else {
        return {
          padding: '0 6px',
        };
      }
    }
  }, [children, count, maxCount]);
  return (
    <>
      {children ? (
        <div className="badge" style={style}>
          {children}
          {dot ? (
            <span
              className="dot"
              style={{ ...dotStyle, right: `${offset[0]}px`, top: `${offset[1]}px` }}
            ></span>
          ) : text ? (
            <span className="badge-text">{text}</span>
          ) : (
            <span className="count" style={{ ...dotStyle, ...countStyle }}>
              {computedCount}
            </span>
          )}
        </div>
      ) : (
        <div className="no-child-badge" style={{ ...style, ...dotStyle, ...countStyle }}>
          {computedCount}
        </div>
      )}
    </>
  );
};

export default memo(Badge);

基本props中都是来配置徽标显示的,比如文本徽标、数字徽标、最大值配置这些的。

最后留一下Concis组件库线上地址吧~

开源不易,欢迎学习和体验,喜欢请多多支持,有问题请留言。