NextJS開發(fā):封裝shadcn/ui中的AlertDialog組件

shadcn/ui很靈活可以方便的自己修改class樣式,但是僅僅一個確認(rèn)刪除彈窗犁河,需要拷貝太多代碼和導(dǎo)入太多包姊扔,重復(fù)的代碼量太多惠奸,不利于代碼維護(hù)。所以進(jìn)一步封裝以符合項目中使用恰梢。

封裝cx-alert-dialog.tsx

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

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

/** 
 * Button擴(kuò)展佛南,增加圖標(biāo)功能 
 * <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組件

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="確認(rèn)刪除?" cancelText="取消" okText="刪除"
        onClose={() => setDelAlertVisible(false)} onOk={() => handleDelAlertOk()} loading={delAlertLoading} disabled={delAlertLoading}/>
    )
  }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市嵌言,隨后出現(xiàn)的幾起案子嗅回,更是在濱河造成了極大的恐慌,老刑警劉巖摧茴,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绵载,死亡現(xiàn)場離奇詭異,居然都是意外死亡苛白,警方通過查閱死者的電腦和手機(jī)娃豹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事潭千。” “怎么了躯畴?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長薇芝。 經(jīng)常有香客問我蓬抄,道長,這世上最難降的妖魔是什么夯到? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任嚷缭,我火速辦了婚禮,結(jié)果婚禮上黄娘,老公的妹妹穿的比我還像新娘峭状。我一直安慰自己克滴,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布优床。 她就那樣靜靜地躺著劝赔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪胆敞。 梳的紋絲不亂的頭發(fā)上着帽,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天,我揣著相機(jī)與錄音移层,去河邊找鬼仍翰。 笑死,一個胖子當(dāng)著我的面吹牛观话,可吹牛的內(nèi)容都是我干的予借。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼频蛔,長吁一口氣:“原來是場噩夢啊……” “哼灵迫!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起晦溪,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤瀑粥,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后三圆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體狞换,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年舟肉,在試婚紗的時候發(fā)現(xiàn)自己被綠了修噪。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡度气,死狀恐怖割按,靈堂內(nèi)的尸體忽然破棺而出膨报,到底是詐尸還是另有隱情磷籍,我是刑警寧澤,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布现柠,位于F島的核電站院领,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏够吩。R本人自食惡果不足惜比然,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望周循。 院中可真熱鬧强法,春花似錦万俗、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蓖墅,卻和暖如春库倘,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背论矾。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工教翩, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人贪壳。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓饱亿,卻偏偏與公主長得像,于是被迫代替她去往敵國和親闰靴。 傳聞我的和親對象是個殘疾皇子路捧,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容