react EUI 《消息通知》组件封装

如题基于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)

react EUI 《消息通知》组件封装

 

 

 

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

 

上一篇:SQL Server PARTITION FUNCTION(分区)


下一篇:MySQL主键约束