前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >微前端无界多页签实现

微前端无界多页签实现

作者头像
星宇大前端
发布2023-03-06 15:56:09
1.2K0
发布2023-03-06 15:56:09
举报
文章被收录于专栏:大宇笔记大宇笔记

qiankun 用了一段时间有了两点体会,第一个是接入有点复杂,第二是沙箱隔离总是这里那里有点问题,所以打算换一下无界。

背景

在程序员的眼里,多页签这个需求确实是影响应能,但是在大中国这种需求客户不会不提的,所以微前端都要解决这个问题。

官方现在没有这个demo,在群里沟通了下也没有标准答案,按照以往的标准实现了一个版本。

结果演示

无界多页签demo

实现原理

  1. 利用tabs 显示隐藏实现
  2. 每一个子应用都是一个组件

注意点: 无界子应用name 不可以重复,可以跟注册时候name 不一致。

核心代码编写

import React, { useRef, useState } from 'react';
import { Button, Tabs } from 'antd';
import WujieReact from 'wujie-react';

type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

const defaultPanes = [
  { label: `Tab 1`, children:<WujieReact width="100%" height="100%" name='react18' url='//localhost:8001/dashboard'   alive={true}/>, key: "1" },
  { label: `Tab 2`, children:<WujieReact width="100%" height="100%" name='react18-1' url='//localhost:8001/state'   alive={true}/>, key: "2"},
]

const App: React.FC = () => {
  const [activeKey, setActiveKey] = useState(defaultPanes[0].key);
  const [items, setItems] = useState(defaultPanes);
  const newTabIndex = useRef(0);

  const onChange = (key: string) => {
    setActiveKey(key);
  };

  const add = () => {
    const newActiveKey = `newTab${newTabIndex.current++}`;
    setItems([...items, { label: 'New Tab', children: <WujieReact width="100%" height="100%" name={`react${newActiveKey}`} url='//localhost:8001/dashboard'   alive={true}/>, key: newActiveKey }]);
    setActiveKey(newActiveKey);
  };

  const remove = (targetKey: TargetKey) => {
    const targetIndex = items.findIndex((pane) => pane.key === targetKey);
    const newPanes = items.filter((pane) => pane.key !== targetKey);
    if (newPanes.length && targetKey === activeKey) {
      const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex];
      setActiveKey(key);
    }
    setItems(newPanes);
  };

  const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button onClick={add}>ADD</Button>
      </div>
      <Tabs
        hideAdd
        onChange={onChange}
        activeKey={activeKey}
        type="editable-card"
        onEdit={onEdit}
        items={items}
      />
    </div>
  );
};

export default App;

代码仓库地址:https://github.com/RainManGO/wujie-tabs-demo

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-02-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景
  • 结果演示
  • 实现原理
  • 核心代码编写
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档