qiankun 用了一段时间有了两点体会,第一个是接入有点复杂,第二是沙箱隔离总是这里那里有点问题,所以打算换一下无界。
背景
在程序员的眼里,多页签这个需求确实是影响应能,但是在大中国这种需求客户不会不提的,所以微前端都要解决这个问题。
官方现在没有这个demo,在群里沟通了下也没有标准答案,按照以往的标准实现了一个版本。
结果演示
无界多页签demo
实现原理
- 利用tabs 显示隐藏实现
- 每一个子应用都是一个组件
注意点: 无界子应用name 不可以重复,可以跟注册时候name 不一致。
核心代码编写
代码语言:javascript复制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