reactjs – 从React应用程序加载Sass并将CSS文本注入父文档
发布时间:2020-12-15 16:15:28 所属栏目:百科 来源:网络整理
导读:我有一个React应用程序,通过一些填充程序 JavaScript加载到父文档中: 创建 iframe元件 创建一个 div 注入 style标记到 head为了设置插入的 div样式 粗略地说,这可以使用以下方法: // example.jsx// Require the css using css-loaderconst styles = requir
我有一个React应用程序,通过一些填充程序
JavaScript加载到父文档中:
>创建< iframe>元件 粗略地说,这可以使用以下方法: // 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是否存在. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |