NextJS开发:封装shadcn/ui中的AlertDialog确认对话框

news/2024/7/15 19:34:19 标签: nextjs, typescript, react.js

shadcn/ui很灵活可以方便的自己修改class样式,但是仅仅一个确认删除弹窗,需要拷贝太多代码和导入太多包,重复的代码量太多,不利于代码维护。所以进一步封装以符合项目中使用。

封装cx-alert-dialog.tsx

typescript">import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"
import { CustomButton } from "./custom-button"

export const CxAlertDialog = (props: {
  visible: boolean, 
  title?: string, 
  content?: string, 
  cancelText?: string, 
  okText?: string,
  okColor?: string,
  loading?: boolean,
  disabled: boolean,
  onClose: ()=>void,
  onOk: ()=>void,
}) => {

  const buildOkButton = () => {
    if(props.okColor == "red") {
      return (
        <CustomButton variant="destructive" loading={props.loading} disabled={props.disabled} onClick={props.onOk}>{props.okText}</CustomButton>
      )
    }
    else {
      return (
        <CustomButton loading={props.loading} disabled={props.disabled} onClick={props.onOk}>{props.okText}</CustomButton>
      )
    }
  }

  return (
    <>
      <AlertDialog open={props.visible}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{props.title}</AlertDialogTitle>
            <AlertDialogDescription>
              {props.content}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={props.onClose} disabled={props.disabled}>{props.cancelText}</AlertDialogCancel>
            { buildOkButton() }
            {/* {
              props.okColor == "red"
              ?
              <AlertDialogAction className="bg-red-500 hover:bg-red-600" onClick={props.onOk}>{props.okText}</AlertDialogAction>
              :
              <AlertDialogAction onClick={props.onOk}>{props.okText}</AlertDialogAction>
            } */}
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

custom-button.tsx

typescript">"use client"
import React, { MouseEventHandler } from "react";
import { Button } from "../ui/button";
import LcIcon from "./lc-icon";
import { cn } from "@/lib/utils";

/** 
 * Button扩展,增加图标功能 
 * <CustomButton icon="Loader" onClick={handleSubmit}>Button</CustomButton>
 * */
export const CustomButton = (props: {
  variant?: string,
  size?: string,
  className?: string,
  iconClassName?: 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={cn("animate-spin", props.iconClassName ?? 'mr-1' )}/>
    }
    else if(props.icon != null) {
      return <LcIcon name={props.icon} size={16} className={props.iconClassName ?? 'mr-1'}/>
    }
    return ""
  }

  return (
    <Button size={props.size as any ?? "default"} variant={props.variant as any ?? "default"} type={props.type ?? 'button' as any} className={props.className} disabled={props.disabled} onClick={props.onClick}>
      { buildIcon() }
      { props.children }
    </Button>
  )
}

使用CxAlertDialog组件

typescript">const [delAlertVisible, setDelAlertVisible]:[boolean, Dispatch<SetStateAction<boolean>>] = React.useState(false);
  const [delAlertLoading, setDelAlertLoading]:[boolean, Dispatch<SetStateAction<boolean>>] = React.useState(false);
  const currOperId = useRef(BigInt(0))
  const handleDelAlertOk = async () => {
    setDelAlertLoading(true)
    await ChapterApi.del(Number(props.docId), currOperId.current).catch((e) => ErrUtils.apiHandle(e)).then((resp)=>{
      //console.log(resp)
      if(!resp) return
      if(resp?.code == RespCode.Success) {
        setDelAlertVisible(false)
        ToastUtils.success({ msg: resp?.msg })
        currChapterId.current = ""
        refresh()
      } else {
        ToastUtils.error({ msg: resp?.msg ?? "22" })
      }
    })
    .finally(()=>{
      setDelAlertLoading(false)
    })
  }

  const buildDel = () => {
    return (
      <CxAlertDialog visible={delAlertVisible} okColor="red" title="提示" content="确认删除?" cancelText="取消" okText="删除"
        onClose={() => setDelAlertVisible(false)} onOk={() => handleDelAlertOk()} loading={delAlertLoading} disabled={delAlertLoading}/>
    )
  }

http://www.niftyadmin.cn/n/5224707.html

相关文章

【HDFS】ActiveNamenodeResolver#getNamespaces 方法调用点梳理

获取所有的注册在router里的active状态的集群。 /*** Get a list of all namespaces that are registered and active in the* federation.** @return List of name spaces in the federation* @throws IOException Throws exception if the namespace list is not* av…

C#-串口通信入门及进阶扩展

目录 一、串口相关参数介绍 1、端口&#xff08;COM口&#xff09; 2、波特率&#xff08;Baud rate&#xff09; 3、起始位 4、停止位&#xff08;StopBits&#xff09; 5、数据位 6、校验位 7、缓存区 二、串口通信助手 三、虚拟串口工具 四、进阶扩展 1、位运算…

算法----确定两个字符串是否接近

题目 如果可以使用以下操作从一个字符串得到另一个字符串&#xff0c;则认为两个字符串 接近 &#xff1a; 操作 1&#xff1a;交换任意两个 现有 字符。 例如&#xff0c;abcde -> aecdb 操作 2&#xff1a;将一个 现有 字符的每次出现转换为另一个 现有 字符&#xff0c…

Go使用logrus框架

Go中使用logrus框架将日志保存在文件和控制台输出 安装 go get github.com/sirupsen/logrus go get github.com/lestrrat-go/file-rotatelogs go get github.com/rifflock/lfshook完整代码 import ("fmt"rotatelogs "github.com/lestrrat-go/file-rotatelogs…

视频号小店需要办理营业执照吗?入驻都需要什么条件?一篇详解!

我是电商珠珠 视频号小店需要办理营业执照吗&#xff1f;入驻都需要什么条件&#xff1f; 这是新手总会问到的问题&#xff0c;我做视频号小店也已经一年了。接下来&#xff0c;我就来给大家详细的讲一下。 视频号小店需要营业执照吗&#xff1f; 需要&#xff0c;营业执照…

外贸网站的推广技巧有哪些?

在当今的互联网时代&#xff0c;外贸网站的数量和竞争程度都在不断增加。要想在众多的外贸网站中脱颖而出&#xff0c;提高网站的知名度和访问量&#xff0c;就需要采取有效的推广技巧。以下是一些实用的外贸网站推广技巧&#xff1a; 1.确定目标市场和受众 在推广外贸网站之…

sqli-labs靶场详解(less29-less31)

less-29 提示有最好的防火墙 小白原因 这种题型没见过 先自己测试一下 ?id1 to use near 1 预计可以使用报错注入 和单引号有关的注入点 ?id1 and 11 成功 ?id1 and 12 失败 确实是单引号字符型注入点 ?id1;%00 id1%27;%00 获取到了%00空字符&#xff08;原因就是服务器获取…

玄学调参实践篇 | 深度学习模型 + 预训练模型 + 大模型LLM

&#x1f60d; 这篇主要简单记录一些调参实践&#xff0c;无聊时会不定期更新~ 文章目录 0、学习率与batch_size判断1、Epoch数判断2、判断模型架构是否有问题3、大模型 - 计算量、模型、和数据大小的关系4、大模型调参相关论文经验总结5、训练时模型的保存 0、学习率与batch_s…