File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11import * as React from 'react' ;
22import { createPortal } from 'react-dom' ;
33
4+ function isShadowDomSupported ( ) {
5+ return typeof window !== 'undefined' && ! ! HTMLElement . prototype . attachShadow ;
6+ }
7+
48export 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 ) }
You can’t perform that action at this time.
0 commit comments