NextJS开发:shadcn/ui中Button组件扩展增加图标

shadcn/ui组件比较灵活,但是功能相比ant之类组件还是缺少太多功能,本文为shadcn/ui为button组件增加图标,加载中动画等效果。

  1. 安装Lucide
npm install lucide
  1. Lucide组件
import { cn } from '@/lib/utils';
import { icons } from 'lucide-react';

const LcIcon = ({ name, color, size, className }: { name: string, color?: string, size: number, className?: string}) => {
  const LucideIcon = (icons as any)[name];
  if(LucideIcon == null) {
    return <></>
  }
  if(color != null) {
    return <LucideIcon color={color} size={size} />
  } else {
    return <LucideIcon size={size} className={cn("", className)}/>
  }
};

export default LcIcon;
  1. 创建组件CustomButton
"use client"
import React, { MouseEventHandler } from "react";
import { Button } from "../ui/button";
import LcIcon from "./lc-icon";

/** 
 * Button扩展,增加图标功能 
 * <CustomButton icon="Loader" onClick={handleSubmit}>Button</CustomButton>
 * */
export const CustomButton = (props: {
  className?: string, 
  icon?: string, 
  loading?: boolean
  disabled?: boolean,
  type?: string,
  onClick?: MouseEventHandler<HTMLButtonElement>,
  children?: any
}) => {

  const buildIcon = () => {
    if(props.loading != null && props.loading) {
      return <LcIcon name="Loader" size={16} className="mr-1 animate-spin"/>
    }
    else if(props.icon != null) {
      return <LcIcon name={props.icon} size={16} className="mr-1"/>
    }
    return ""
  }

  return (
    <Button type={props.type ?? 'button' as any} className={props.className} disabled={props.disabled} onClick={props.onClick}>
      { buildIcon() }
      { props.children }
    </Button>
  )
}
  1. 组件使用,

显示加载中

import { CustomButton } from "@/components/app/custom-button";

<CustomButton loading={true} disabled={true} >测试</CustomButton>

显示图标

import { CustomButton } from "@/components/app/custom-button";

<CustomButton icon="Home">测试</CustomButton>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ArslanRobot

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值