代码之家  ›  专栏  ›  技术社区  ›  devamat

材质UI全局css变量

  •  0
  • devamat  · 技术社区  · 5 年前

    我想声明一些css变量,我将在我的组件中重用它们。以下是使用纯css的方法:

    :root {
      --box-shadow: 0 2px 5px -1px rgba(0, 0, 0, 0.3);
    }
    

    然后使用如下:

    .my-class {
      box-shadow: var(--box-shadow);
    }
    

    如何使用useStyles实现同样的效果?我尝试了以下方法但没有成功:

    const theme = createMuiTheme({
      shadowing: {
        boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
      }
    });
    

    我的主应用程序在

    <ThemeProvider theme={theme}>
      <App />
    </ThemeProvider>
    

    我试着在我的组件中使用它:

    const useStyles = makeStyles(theme => ({
      workImage: {
        boxShadow: theme.shadowing,
      },
    }));
    

    但它不起作用。

    1 回复  |  直到 5 年前
        1
  •  1
  •   ryuken73    5 年前

    “createMuiTheme”函数接受具有有限键集的对象(调色板、排版、间距等)

    const theme = {
      shadowing: {
         boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
      }
    };
    
        2
  •  5
  •   devamat    5 年前

    在我的例子中,我必须同时使用createMuiTheme和自定义变量。为了实现这个目标,我做了如下工作。

    const theme = createMuiTheme({
      typography: {
        fontFamily: "verdana",
      },
    });
    

    然后我创建了一个单独的对象,在其中添加变量:

    const cssVariables = {
      shadowing: {
         boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
      }
    };
    

    <ThemeProvider theme={{ ...theme, ...cssVariables }}>
    

    最后,要访问变量:

    const useStyles = makeStyles(theme => ({
      workImage: {
        boxShadow: theme.shadowing.boxShadow,
      },
    }));