Material UI global css variables

限于喜欢 提交于 2020-08-09 07:18:41

问题


I would like to declare some css variables that I will reuse among my components. This is how you do it with plain css:

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

That would then be used as follows:

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

How can I achieve the same with useStyles? I tried the following with no avail:

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

My main App is enclosed within

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

I tried using it in my component:

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

But it's not working.


回答1:


"createMuiTheme" function accepts object with limited set of keys.(palette, Typography, spacing...etc)

You can use just normal object.

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



回答2:


In my case I had to use both createMuiTheme and custom variables. To achieve it I did as follows.

First I created a theme with createMuiTheme

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

Then I created a separated object where I add my variables:

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

Then I pass the two objects to my ThemeProvider:

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

And finally, to access the variable:

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


来源:https://stackoverflow.com/questions/59231839/material-ui-global-css-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!