react根据路由变化展示的全局弹窗需求

该代码段重写了浏览器的`pushState`和`replaceState`方法,以便在调用这些方法时触发自定义事件。当路由变化时,会检查是否需要弹出全局对话框。如果当前路径在预定义的路由列表中,会创建并渲染一个`DialogComp`组件。此外,代码还添加了事件监听器,以便在`pushState`和`replaceState`事件发生时关闭或显示对话框。
摘要由CSDN通过智能技术生成
/**
 * 重写history的pushState和replaceState
 * @param action pushState|replaceState
 * @return {function(): *}
 */
const wrapEventHandle = (action) => {
  // 获取pushState或replaceState方法
  const handle = history[action];
  return function () {
    // 经过包装的pushState或replaceState
    const wrapper = handle.apply(this, arguments);

    // 定义名为action的事件
    const e = new Event(action);
    
    // 将调用pushState或replaceState时的参数作为state属性放到事件参数event上
    e.state = { ...arguments, target: this };
    // 调用pushState或replaceState时触发该事件
    window.dispatchEvent(e);
    return wrapper;
  };
};

main.js写入全局弹窗

import ReactDom from 'react-dom';

const ROUTER_LIST = []; // 包含配置的路由地址才弹窗
let dive: any = null;
const body = document.body || document.documentElement;
const dialog = () => {
  const { pathname } = window.location;
  const flag = ROUTER_LIST.includes(pathname);
  // 业务逻辑
  // ...
  dive = document.createElement('div');
  body.appendChild(dive);
  ReactDom.render(<DialogComp />, dive);
};
isVnADialog(); // 初始刷新调用一次

// 修改原始定义
history.pushState = wrapEventHandle('pushState');
history.replaceState = wrapEventHandle('replaceState');

// 监听自定义的事件
window.addEventListener('pushState', (e: any) => {
  // console.info('pushState', e.state);
  if (e.state) {
    body.contains(dive) && body.removeChild(dive);
    dialog();
  }
});
window.addEventListener('replaceState', (e: any) => {
  // console.info('replaceState', e.state);
  if (e.state) {
    body.contains(dive) && body.removeChild(dive);
    dialog();
  }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值