React-component-library--Button

文章展示了如何在React中封装一个Button组件,包括不同类型的按钮、尺寸、禁用状态、圆角、虚线边框及加载状态等特性,并提供了详细的接口定义和使用示例。此外,还提到了GitHub上的组件库地址。

 Button 按钮

使用以及文档如图:

 

 

 

封装代码如下所示

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

interface ButtonProps {
  //自定义button接口
  /**
   * @description 按钮主题
   * @default primary
   */
  type?: String;
  /**
   * @description 宽度
   */
  width?: Number;
  /**
   * @description 高度
   */
  height?: Number;
  /**
   * @description 禁用状态
   * @default false
   */
  disabled?: Boolean;
  /**
   * @description 字体按钮
   * @default false
   */
  circle?: Boolean;
  /**
   * @description 按钮边框为虚线
   * @default false
   */
  dashed?: Boolean;
  /**
   * @description 加载状态
   * @default false
   */
  loading?: Boolean;
  /**
   * @description 按钮点击回调事件
   */
  onClick?: Function | undefined;
}

interface ButtonStyle {
  //button样式接口
  width?: String;
  height?: String;
  borderRadius?: String;
  border?: String;
  cursor?: String;
}

type NativeButtonProps = Omit<React.ButtonHTMLAttributes<HTMLElement>, 'type'>; //原生button接口

const Button: FC<ButtonProps & NativeButtonProps> = memo((props) => {
  const {type, width, height, disabled, circle, dashed, loading, onClick, children} = props;

  const buttonStyle = useMemo(() => {
    if (!type && type !== 'danger' && type !== 'warning' && type !== 'warning' && type !== 'text') {
      return 'primary';
    }
    return type as any;
  }, [type]);
  const buttonSize = useMemo(() => {
    var size: ButtonStyle = {
      width: '100px',
      height: '40px',
    };
    if (width) {
      size.width = width + 'px';
    }
    if (height) {
      size.height = height + 'px';
    }
    if (circle) {
      size = {...size, borderRadius: '50%'};
    }
    if (dashed && type === 'text') {
      size = {...size, border: '1px dashed #ccc'};
    }
    if (disabled) {
      size = {...size, cursor: 'not-allowed'};
    }
    return size;
  }, [width, height, circle, dashed]);
  return (
    <div className="button">
      <button
        className={buttonStyle}
        style={buttonSize as any}
        disabled={disabled ? true : false}
        onClick={onClick as undefined}
      >
        {loading && <div className="loading1"/>}
        {children}
      </button>
    </div>
  );
});

export default Button;

GitHub-address:GitHub - username-boy/react-component-library-view: this is a react-component-library .this is a react-component-library . Contribute to username-boy/react-component-library-view development by creating an account on GitHub.https://github.com/username-boy/react-component-library-view/

good  luck !

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值