材质UI CSS加载顺序

问题描述:

我很难理解应该如何构建我的项目. 我正在使用材质UI和CSS模块进行反应. 问题是上帝知道为什么,来自MUI的所有样式在标头底部都与css模块样式相同. 经过一番研究,我发现了两种解决方案:

I am having hard time understanding how I should structer my project. I am using react with material UI and css modules. Problem is that god knows why, all styling from MUI loads at the bottom of the header same as css module styling. After some research I found two solutions:

  1. 在CSS模块内部使用!important很糟糕.
  2. 更改注射顺序 https://material-ui.com/guides/互操作性/#css模块

第二个问题是,在多组件项目中,这将是一个可怕的麻烦,在每次引入新组件时,您都必须手动加载该组件,如示例中所示.我是否缺少明显的东西?您有什么想法可以更轻松地更改加载顺序吗?

Problem with the second one is that it would be terrible tedieouse in a multi component project where every time you introduce a new component you have to load it manually as in the example. Am I missing something obvious? Do you have any ideas how to easier change the load order?

我认为您可能会误解示例中的某些内容.您无需针对每个组件执行任何操作来更改加载顺序. 步骤如下:

I think you may be misunderstanding something in the example. There isn't anything you need to do on a per-component basis to change the load order. The steps are as follows:

1.在您的index.html中,向您想要插入jss CSS的头部添加<!-- jss-insertion-point -->之类的注释.

1. In your index.html add a comment like <!-- jss-insertion-point --> into the head where you would like the jss CSS to be inserted.

2.在您的index.js(或呈现层次结构顶部或附近的某个位置)中,创建jss配置以指示插入点注释的名称:

2. In your index.js (or somewhere at or near the top of your rendering hierarchy) create the jss configuration to indicate the name of the insertion point comment:

import JssProvider from "react-jss/lib/JssProvider";
import { create } from "jss";
import { jssPreset } from "@material-ui/core/styles";

const jss = create({
  ...jssPreset(),
  // We define a custom insertion point that JSS will look for injecting the styles in the DOM.
  insertionPoint: "jss-insertion-point"
});

3.在JssProvider中包装您的*元素,以使这些配置发挥作用(无特定于组件的步骤):

3. Wrap your top-level element in the JssProvider to put those configurations in play (no component-specific steps):

function App() {
  return (
    <JssProvider jss={jss}>
      <div className="App">
        <Button>Material-UI</Button>
        <Button className={styles.button}>CSS Modules</Button>
      </div>
    </JssProvider>
  );
}

我已经创建了一个与Material-UI文档所指代的CodeSandbox相似的代码,只是该代码使用了create-react-app起点,因此依赖项更加简单.

I've created a CodeSandbox similar to the one pointed at by the Material-UI documentation except that this one uses the create-react-app starting point, so the dependencies are simpler.