【问题标题】:Is there any way to change where Material-UI adds style tag html elements?有什么方法可以改变 Material-UI 添加样式标签 html 元素的位置吗?
【发布时间】:2020-11-12 09:48:22
【问题描述】:

Material-UI 将生成的样式标签添加到<header />,这当然是样式的标准位置,但是我需要将我的样式标签添加到不同的 html 元素中。

我正在寻找一种将遗留 CodeIgniter PHP 应用程序转换为 React 的方法。我有一个计划,但问题是这个遗留应用程序正在使用引导程序,这会弄乱我的 React 组件。

计划是重置 div 中的所有样式并在其中渲染 React 组件。类似:

<div class="clearcss">
    <div>
        <style type="text/css"></style> // material ui style tags
        <div id="react-component"></div>
    </div>
</div>

不幸的是,因为 Material ui 将其所有样式添加到标题 Material ui 样式也被重置,但如果我可以更改 Material ui 放置样式标签的位置,那么我想我可以让它工作。

【问题讨论】:

    标签: reactjs material-ui jss


    【解决方案1】:

    实际上,在 JSS documentation 中,我找到了一些示例,这些示例展示了如何在 &lt;head /&gt; 之外指定插入点。

    连同 Ryan 指向材料 ui documentation 的评论,我能够实现我想要的。

    JSS 支持两种方式为样式指定自定义插入点:

    1. 通过添加 html 注释(例如 &lt;!-- custom-jss-insertion-point --&gt;)。这仅支持 &lt;head&gt; 中的插入点。

    2. 通过指定一个元素(例如insertionPoint: document.getElementById("custom-jss-insertion-point"))。这种方法支持文档正文中的插入点。

    这是第二种方法所需的工作示例:

    index.html -- 添加一个将插入样式的元素

    ...
      <body>
        <noscript>
          You need to enable JavaScript to run this app.
        </noscript>
        <div id="custom-jss-insertion-point"></div>
        <div id="root"></div>
      </body>
    ...
    

    App.js -- 告诉 JSS 自定义插入点

    import React from "react";
    import { create } from "jss";
    import { StylesProvider, jssPreset } from "@material-ui/core/styles";
    import Button from "@material-ui/core/Button";
    
    const jss = create({
      ...jssPreset(),
      // Define a custom insertion point that JSS will look for when injecting the styles into the DOM.
      insertionPoint: document.getElementById("custom-jss-insertion-point")
    });
    
    export default function App() {
      return (
        <StylesProvider jss={jss}>
          <div className="App">
            <Button variant="contained" color="primary">
              Hello
            </Button>
          </div>
        </StylesProvider>
      );
    }
    

    这会导致添加样式,如下图所示:

    如果你使用 React 渲染插入点元素,你需要在配置 JSS 时尝试调用 document.getElementById("custom-jss-insertion-point") 之前确保该元素存在。如果可以这样做,我建议在 React 之外渲染插入点元素(如示例中所示)以避免操作顺序复杂化。

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多