在为基于材质UI的前端设置样式时,我感到困惑。
在下面的示例代码中,theme
来自哪里?主题的效果是什么?
import React from "react";
import Container from "@material-ui/core/Container";
const useStyles = makeStyles(theme => ({
root: {
height: "100%"
}
}));
const Sample = props => {
const classes = useStyles();
return (
<Container className={classes.root}/>
);
}
有一个主题提供商,称为ThemeProvider
-
主题材料文档
-
更自定义的使用高级主题
<ThemeProvider theme={outerTheme}>
<Checkbox defaultChecked />
<ThemeProvider theme={innerTheme}>
<Checkbox defaultChecked />
</ThemeProvider>
</ThemeProvider>
它为子组件提供了主题,我们通常在项目的顶层定义它。
然后您可以通过多种方式访问上面定义的Theme
- 访问组件
例如,对于经典组件,我们有主题HOC
import { withTheme } from '@material-ui/core/styles';
function DeepChildRaw(props) {
return <span>{`spacing ${props.theme.spacing}`}</span>;
}
const DeepChild = withTheme(DeepChildRaw);
对于功能组件,我们有useTheme挂钩
import { useTheme } from '@material-ui/core/styles';
function DeepChild() {
const theme = useTheme();
return <span>{`spacing ${theme.spacing}`}</span>;
}
您可以在makeStyles和createStyles中使用它们作为正常
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles(theme => ({
root: {
width: theme.spacing(1);
}
}));
import { createStyles } from '@material-ui/core/styles';
const styles = (theme: Theme) => createStyles({
root: {
width: theme.spacing(1);
}
})