reactjs - 如何在使用 "react-frame-component"库创建的 IFrame 中加载 webpack 提供的 css?

标签 reactjs iframe webpack webpack-style-loader

我正在尝试在 iframe 内渲染我的 React 组件。我通过使用“react-frame-component”库让它工作。问题在于样式是在 iframe 外部“head”元素的末尾加载的。我想将其更改为加载到“iframe”元素的“head”内。 我正在使用 Webpack 生成包含 JS 和 CSS 的包,我发现我可以通过设置选项“insertInto”来更改“style-loader”加载样式的位置,但这会引发错误:

Uncaught Error: Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.

这是我的 React 组件:

import Frame from 'react-frame-component'
...
ReactDOM.render(
  <Frame id="someId">
    <Provider store={Store.get()}>
      <Container/>
    </Provider>,
  </Frame>,
  document.body
);

这是我在 Webpack 配置中的“样式加载器”:

{
  loader: 'css-loader',
  options: {
    insertInto: () => document.querySelector("#someId"),
  },
}

我认为问题是当 webpack 尝试包含样式时组件没有呈现。怎么解决这个问题?

最佳答案

您需要将样式作为占位符加载到临时元素中,然后使用 Javascript 将这些样式克隆到新框架中。

// index.html
...
<div id="dynamic-styles"></div>
...
// webpack.config.js
...
{
  loader: 'css-loader',
  options: {
    insertInto: () => document.getElementById("dynamic-styles"),
  },
}
...
// some.js
...

const stylesContainer = document.getElementById('dynamic-styles');
const frame = document.getElementById('someID');
const frameHead = frame.contentWindow.document.head;

[...stylesContainer.children].forEach(styleNode => {
  const newStyle = document.createElement('style');
  newStyle.textContent = styleNode.textContent;

  frameHead.appendChild(newStyle);
});

我还没有测试过上面的代码片段,但我知道这个概念是有效的。我觉得这很能说明问题。

可能有更好的方法来做到这一点,但我还没有进行足够的研究来弄清楚。如果能够让 webpack 制作单独的样式包,这样每个配置的框架就可以自动延迟加载它自己专用的捆绑 css,那就太好了

关于reactjs - 如何在使用 "react-frame-component"库创建的 IFrame 中加载 webpack 提供的 css?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50206457/

相关文章:

javascript - 在 Webpack 和 React.js 中设置代码拆分

reactjs - 样式组件再水化成本高吗?

reactjs - 如何在React中共享对象?

javascript - react JS : Does my Application work correctly?

javascript - iframe src 函数调用不断被触发

WordPress 弹出 Iframe Youtube Https 与 PrettyPhoto

javascript - 该网站如何以叠加方式显示此 YouTube 视频?

Webpack 4.引用错误: require is not defined

javascript - 有没有一种方法可以根据用户的选择动态显示带有钩子(Hook)的多个文本字段? (值和 onChange)

javascript - Chrome 没有加载所有 webpack JS 源文件,但是 Firefox + Chrome Incognito 可以