gpt4 book ai didi

reactjs - 从 React 应用程序加载 Sass 并将 CSS 文本注入(inject)父文档

转载 作者:行者123 更新时间:2023-12-03 13:50:06 26 4
gpt4 key购买 nike

我有一个 React 应用程序,它通过一些 shim JavaScript 加载到父文档中:

  • 创建 <iframe>元素
  • 创建 <div>
  • 注入(inject) <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);

这使用css-loader在我们的 Webpack 配置中,以获得 require().toString()用于设置 cssText动态地。

虽然这有效,但我不知道这是否理想。我们更愿意编写 Sass 并获得 @import 的好处引入其他 CSS(例如重置),并获得其他 Sass 工具的好处。

有没有更好的方法可以达到注入(inject)<style>相同的结果将文本写入此父文档而不牺牲我们使用我们喜欢的工具的能力?

最佳答案

安装react-helmet,然后在你的react组件中尝试这个:

<Helmet>
<style>
// Insert CSS string here
</style>
</Helmet>

另一个选项是直接在父级中加载 sass,但将其所有样式控制在一个 sass 函数后面,该函数检查 #react-root 是否存在。

关于reactjs - 从 React 应用程序加载 Sass 并将 CSS 文本注入(inject)父文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51142337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com