我正在尝试使用 React Portal 在 iframe 内渲染 MUI 组件。尽管它们是在 iframe 内渲染的,但当使用 React Portal 在 iframe 内渲染时,它们会丢失所有 thMUI 组件并丢失其样式。有关此主题的所有文档/示例和讨论都与旧版本的 MUI 相关。使用 ShadowDOM 时情况更糟。
MUI 默认使用情感作为样式引擎,@emotion 有一个 CacheProvider 来配置您想要放置样式的位置。
import React, { useState } from 'react'
import { createPortal } from 'react-dom'
import createCache from '@emotion/cache'
import { CacheProvider } from '@emotion/react'
const PreviewIframe = styled('iframe')(() => ({
border: 'none',
height: '100%',
width: '100%'
}))
const PreviewPortal = (props: PreviewPortalProps) => {
const [contentRef, setContentRef] = useState<any>(null)
const mountNode = contentRef?.contentWindow?.document?.body
const cache = createCache({
key: 'css',
container: contentRef?.contentWindow?.document?.head,
prepend: true
})
return (
<PreviewIframe ref={setContentRef}>
{mountNode &&
ReactDOM.createPortal(
<CacheProvider value={cache}>
{props.children}
</CacheProvider>,
mountNode
)}
</PreviewIframe>
)
}
查看这些链接了解更多详细信息。 https://mui.com/material-ui/getting-started/installation/#npm https://emotion.sh/docs/@emotion/cache#container