如題基於EUI封裝個《消息通知》組件
需求,一次調用全項目能用如果按原來的EUI組件,
每個頁面想調用消息通知組件EuiGlobalToastList就得調用DOM跟方法,
比較麻煩現在需要封裝成一句話調用馬上能用比如:
message.success("操作成功", 2000, "內容文字");
message.warning("警告!");
message.danger("操作失敗");
message.primary("普通消息");
以下簡單說說怎么實現
先封裝組件命名為WFToast(名字隨意)
import React, { useState, forwardRef, useImperativeHandle } from 'react'
import { generateId } from '../../utils'
import { EuiGlobalToastList } from '@elastic/eui'
const WFMessage = (props, ref) => {
const [toasts, setToasts] = useState([]);
const addToast = (title, time = 2000, type = "", text = "") => {
let iconType = "";
let color = "";
switch(type){
case "warning":
iconType = "help";
color = "warning";
break;
case "danger":
iconType = "alert";
color = "danger";
break;
case "primary":
iconType = "bell";
color = "primary";
break;
default:
iconType = "check";
color = "success";
};
setToasts([...toasts, {
id: `toast_${generateId()}`,
title: title,
text,
toastLifeTimeMs: time,
iconType, // 圖標: check 成功, help 警告, alert 危險(更多圖標可參考EUI圖標庫)
color // 類型: success, warning, danger, primary
}]);
}
const removeToast = (removedToast) => {
setToasts(toasts.filter((toast) => toast.id !== removedToast.id))
}
useImperativeHandle(ref, () => ({addToast}));
return (
<EuiGlobalToastList
toasts={toasts}
dismissToast={removeToast}
toastLifeTimeMs={2000}
/>
)
}
export default forwardRef(WFMessage);
在跟目錄的index.js路由插入組件WFToast,要注意必須先用函數組件Message再包一層,因為WFToast組件需要用ref調用內部方法addToast(這部分涉及到hook)

餓死了,先發部分吧,明天有空再偷偷發剩下的。。。
