如何在 iframe 中使用 Material UI (mui) 5.0?

问题描述 投票:0回答:1

我正在尝试使用 React Portal 在 iframe 内渲染 MUI 组件。尽管它们是在 iframe 内渲染的,但当使用 React Portal 在 iframe 内渲染时,它们会丢失所有 thMUI 组件并丢失其样式。有关此主题的所有文档/示例和讨论都与旧版本的 MUI 相关。使用 ShadowDOM 时情况更糟。

javascript reactjs iframe material-ui emotion
1个回答
3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.