这个问题的目的是了解幕后发生的事情。每次使用makeStyles()
找到代码时,我都会感觉自己只是在进行纯复制粘贴,而不了解幕后发生的事情。所以我想在这里发布一个问题,以便有人可以帮助我。
我已经在许多React应用程序中看到以下类型的代码。我很想知道当我们打电话给makeStyles()
时发生了什么。因此,我跳入了它的定义,但我不明白它的含义。有人可以帮助我了解如何阅读/理解它。
我在这里了解到的是我正在传递一个名为theme
的参数的函数。通过该函数后,我不知道发生了什么。我也很高兴有人能帮助我解决这个问题。
// Calling makeStyles()
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
},
drawer: {
[theme.breakpoints.up('sm')]: {
width: drawerWidth,
flexShrink: 0,
},
},
appBar: {
marginLeft: drawerWidth,
[theme.breakpoints.up('sm')]: {
width: `calc(100% - ${drawerWidth}px)`,
},
},
menuButton: {
marginRight: theme.spacing(2),
[theme.breakpoints.up('sm')]: {
display: 'none',
},
},
toolbar: theme.mixins.toolbar,
drawerPaper: {
width: drawerWidth,
},
content: {
flexGrow: 1,
padding: theme.spacing(3),
},
}));
//definition of makeStyles()
import { Theme as DefaultTheme } from './createMuiTheme';
import { Styles, WithStylesOptions } from '@material-ui/styles/withStyles';
import { StylesHook } from '@material-ui/styles/makeStyles';
export default function makeStyles<
Theme = DefaultTheme,
Props extends {} = {},
ClassKey extends string = string
>(
styles: Styles<Theme, Props, ClassKey>,
options?: WithStylesOptions<Theme>,
): StylesHook<Styles<Theme, Props, ClassKey>>;
答案 0 :(得分:0)
makeStyles
useStyles
),该函数将在功能组件。stylesOrCreator
。然后,getStylesCreator function将该对象归一化为具有create
属性的对象,该属性指向将返回样式对象的函数。useStyles
函数
makeStyles
开发的函数returned通常称为useStyles
,是custom hook。这意味着只能从函数组件和must be called unconditionally中调用它。useStyles
函数时,几乎没有发生任何事情。该函数知道其stylesCreator,但尚未使用它。通过stylesCreator's options,useStyles
函数知道一个index
,以后将用来确定这些样式相对于其他样式在样式表的<head>
中的位置其他调用makeStyles
/ useStyles
生成的工作表。<head>
生成的样式表的makeStyles/useStyles
中的索引。useStyles
makeStyles
返回的函数。应该从函数组件内部调用它,以获得下面描述的classes
对象。props
对象
props
。然后,它将作为参数传递给任何值是函数的样式规则。classes
对象
classes.rulename
将CSS类应用于元素。<head>
的DOM中添加一个样式表,其中包含每个样式规则的CSS类。当您调用useStyles
函数时,发生了很多魔术。函数的开头是here。这是它执行的关键步骤:
classes
对象中使用的类名。<head>
中适当位置的DOM。答案 1 :(得分:0)
makeStyles(styles,[options])=>钩子 使用挂钩模式将样式表与功能组件链接。
参数
样式(函数|对象):生成样式或样式对象的函数。它将链接到组件。如果您需要访问主题,请使用功能签名。它是第一个参数。
选项(对象[可选]): options.defaultTheme(对象[可选]):
1。如果未通过主题提供程序提供主题,则使用默认主题。
其他键转发到的options参数 jss.createStyleSheet([styles], [options]).。 退货 钩子:钩子。该挂钩可以在功能组件中使用。该文档通常将此返回的钩子useStyles称为。它接受一个参数:样式表中用于“插值”的属性。
示例
import React from 'react';
import { makeStyles } from '@material-ui/styles';
const useStyles = makeStyles({
root: {
backgroundColor: 'red',
color: props => props.color,
},
});
export default function MyComponent(props) {
const classes = useStyles(props);
return <div className={classes.root} />;
}