renderClient.tsx
1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { ApplyPluginsType, Plugin } from '@umijs/runtime';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
interface IOpts {
routes: any[];
plugin: Plugin;
history?: any;
defaultTitle?: string;
rootElement?: string | HTMLElement;
path?: string;
callback?: () => void;
}
function getRootContainer(opts: { routes: any[]; path: string }) {
for (const route of opts.routes) {
if (route.path === opts.path) return route.component;
}
}
export function renderClient(opts: IOpts): any {
let path = opts.path;
if (!path) {
// @ts-ignore
path = window.g_path as string;
}
// 暂不支持子路由
for (const route of opts.routes) {
if (route.routes) {
throw new Error(
`Render failed, child routes is not supported in mpa renderer.`,
);
}
}
const RouteComponent = getRootContainer({ routes: opts.routes, path });
if (!RouteComponent) {
throw new Error(`Render failed, route of path ${path} not found.`);
}
const rootContainer = opts.plugin.applyPlugins({
type: ApplyPluginsType.modify,
key: 'rootContainer',
initialValue: (
<RouteComponent
history={opts.history}
routes={opts.routes}
plugin={opts.plugin}
defaultTitle={opts.defaultTitle}
/>
),
args: {
history: opts.history,
routes: opts.routes,
plugin: opts.plugin,
},
});
if (opts.rootElement) {
const rootElement =
typeof opts.rootElement === 'string'
? document.getElementById(opts.rootElement)
: opts.rootElement;
const callback = opts.callback || (() => {});
// @ts-ignore
ReactDOM[window.g_useSSR ? 'hydrate' : 'render'](
rootContainer,
rootElement,
callback,
);
} else {
return rootContainer;
}
}