我有一个React应用程序,通过一些填充程序 JavaScript加载到父文档中: 创建 iframe元件 创建一个 div 注入 style标记到 head为了设置插入的 div样式 粗略地说,这可以使用以下方法: // example.
>创建< iframe>元件
>创建一个< div>
>注入< style>标记到< head>为了设置插入的< div>样式
粗略地说,这可以使用以下方法:
// example.jsx // Require the css using css-loader const styles = require('../styles/example.css'); // Find the parent document const doc = window.parent.document; // Inject our stylesheet for the widget into the parent document's // HEAD as a style tag const css = styles.toString(); const style = doc.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { // This is required for IE8 and below. style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } doc.head.appendChild(style);
这在我们的Webpack配置中使用了css-loader,以使require().toString()能够动态地设置cssText.
虽然这有效,但我不知道这是否理想.而且我们更喜欢编写Sass并获得@import的好处来引入其他CSS(如重置),并获得Sass的其他工具的好处.
是否有更好的方法可以实现注入< style>的相同结果文本到这个父文档而不牺牲我们使用我们喜欢的工具的能力?
安装react-helmet,然后在您的反应组件中尝试:<Helmet> <style> // Insert CSS string here </style> </Helmet>
另一种选择是将sass直接加载到父级中,但将其所有样式置于sass函数后面,该函数检查#react-root是否存在.