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


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

    1. 安装Lucide
    npm install lucide
    
    • 1
    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    1. 创建组件CustomButton
    "use client"
    import React, { MouseEventHandler } from "react";
    import { Button } from "../ui/button";
    import LcIcon from "./lc-icon";
    
    /** 
     * Button扩展,增加图标功能 
     * Button
     * */
    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    1. 组件使用,

    显示加载中

    import { CustomButton } from "@/components/app/custom-button";
    
    <CustomButton loading={true} disabled={true} >测试</CustomButton>
    
    • 1
    • 2
    • 3

    显示图标

    import { CustomButton } from "@/components/app/custom-button";
    
    <CustomButton icon="Home">测试</CustomButton>
    
    • 1
    • 2
    • 3
  • 相关阅读:
    布隆过滤器原理介绍和典型应用案例
    护网中蓝队都做哪些工作
    HiveSQL中的JOIN ON条件
    【实用工具系列】MathCAD入门安装及快速上手使用教程
    IOT 围炉札记
    Intel酷睿和AMD锐龙
    shellcode 中 null byte 的成因和避免方式总结
    在 LLM 架构中应用多专家模型
    2024年环境安全科学、材料工程与制造国际学术会议(ESSMEM2024)
    Redis创始人开源最小聊天服务器,仅200行代码,几天功夫已获2.8K Star!
  • 原文地址:https://blog.csdn.net/zhbzhb324/article/details/134432851