Skip to content

Commit b848ca1

Browse files
committed
feat: add shadow dom support check and fallback rendering
1 parent 698a066 commit b848ca1

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

src/Body/ShadowComponent.tsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import * as React from 'react';
22
import { createPortal } from 'react-dom';
33

4+
function isShadowDomSupported() {
5+
return typeof window !== 'undefined' && !!HTMLElement.prototype.attachShadow;
6+
}
7+
48
export default function ShadowComponent({
59
children,
610
className,
@@ -10,14 +14,29 @@ export default function ShadowComponent({
1014
}) {
1115
const hostRef = React.useRef<HTMLDivElement>(null);
1216
const [shadowRoot, setShadowRoot] = React.useState<ShadowRoot | null>(null);
17+
const [shadowSupported, setShadowSupported] = React.useState<boolean>(true);
1318

1419
React.useEffect(() => {
20+
// 检查是否支持 Shadow DOM
21+
if (!isShadowDomSupported()) {
22+
setShadowSupported(false);
23+
return;
24+
}
1525
if (hostRef.current && !shadowRoot) {
1626
const shadow = hostRef.current.attachShadow({ mode: 'open' });
1727
setShadowRoot(shadow);
1828
}
1929
}, [shadowRoot]);
2030

31+
// 如果不支持 Shadow DOM,直接渲染 children
32+
if (!shadowSupported) {
33+
return (
34+
<div ref={hostRef} className={className}>
35+
{children}
36+
</div>
37+
);
38+
}
39+
2140
return (
2241
<div ref={hostRef} className={className}>
2342
{shadowRoot && createPortal(children, shadowRoot)}

0 commit comments

Comments
 (0)