如何在div中使用Material UI主题颜色



我制作了一个库,使用了一些Material UI组件,它们根据安装它们的项目提供的主题调整颜色。我还想使用";初级"次级";div上的颜色,因为我希望背景颜色也能适应主题。有办法做到这一点吗?

在按钮中,我唯一需要做的就是

<Button color="secondary"/>

但是,我该如何做与div等价的操作呢?

const MainContainer = styled.div`
background: secondary;
`;

如何使这个次要颜色成为父项目主题的颜色,如按钮中的颜色?

我以前没有style compononent的任何经验。但对于materail-ui,您可以通过两种方式应用color:-

  1. 使用useTheme(仅联机使用-据我所知(,从material-ui/core/styles导入:-
import { useTheme } from 'material-ui/core/styles'
export const Demo = () => {
const theme = useTheme()
return (
<div style={{ backgroundColor: theme.palette.primary.main }}>Hi You!</div>  
)
}
  1. 使用makeStyles(您可以在没有styled-component的情况下单独使用(,从material-ui/core/styles导入
import { makeStyles } from 'material-ui/core/styles'
export const Demo = () => {
const classes = useStyles()
return (
<div className={classes.divStyle}>Hi You!</div>  
)
}
const useStyles = makeStyles(theme => ({
divStyle: {
backgroundColor: theme.palette.primary.main
// or any color
// backgroundColor: 'red'
}
}))

您可以使用useTheme钩子访问theme对象中的颜色。

https://material-ui.com/styles/api/#usetheme-主题

最新更新