如何使用钩子覆盖材质 ui 样式 [英] How override material ui style with hooks
问题描述
我尝试使用类名创建 AppBar,将其夹在页面顶部并悬停在其他带有 React Hooks 和 Material Ui 的 Drawer 上.全部如:
但是当下载并编译同一个项目时就不行了:
查看调试器,样式是内联的.在沙箱中,钩子位于底部:
在浏览器中,当应用程序通过运行启动"运行时,其在顶部:
所以这就是区别,但为什么以及如何解决这个问题?
您可以使用 classes
道具代替 classNames
来覆盖 material-ui 样式.
例如
这里我使用了 root
键来覆盖,还有很多其他的键可以玩.
每个 Material-ui 组件都有一个 api 部分.您将获得此处列出的覆盖键列表.
一些有用的链接 -
https://https://material-ui.com/customization/components/#overriding-styles-with-class-names
https://material-ui.com/api/app-bar/一个>
I try to create AppBar clipped to the page top and hovering over other Drawer with React Hooks and Material Ui using class name. All as described in: https://material-ui.com/demos/drawers/#clipped-under-the-app-bar
So we have
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
height: '100%',
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
},
menuButton: {
marginRight: 20,
[theme.breakpoints.up('md')]: {
display: 'none',
},
},
}));
And reder:
<div className={classes.root}>
<CssBaseline/>
<LoadingResults showLoading={showLoadingSpinner}/>
<AppBar position="fixed" className={classes.appBar} >
...
</AppBar>
....
Problem is that the style applied with className is added last of the element so its not overriding the orignal style:
class="MuiPaper-root-12 MuiPaper-elevation4-18 MuiAppBar-root-3 MuiAppBar-positionFixed-4 MuiAppBar-colorPrimary-10 mui-fixed Hook-appBar-1b6f20g"
I know I can use inline styles but wonder to know if I can override styles using classNames with hooks as it was with "legacy" component approach ?
Here is sandbox: https://codesandbox.io/s/w7njqorzy7?fontsize=14
What happens is that in sandbox the code works ok (appbar over lefthand side container)
But when the same project is downloaded and compiled it's not ok:
Looking at the debuger the styles are inline. In the sandbox hooks are at the bottom:
In the browser when app is run via "run start" its on top:
So this is the difference, but why and how to fix this ?
You can override material-ui styles with classes
props instead of classNames
.
For example
<AppBar position="fixed" classes={{root: classes.appBar}}>
Here I have used root
key to override, there are many other keys with which you can play around.
Every Material-ui component have an api section. You will get list of overriding keys listed there.
Some useful links -
https://https://material-ui.com/customization/components/#overriding-styles-with-class-names
https://material-ui.com/api/app-bar/
这篇关于如何使用钩子覆盖材质 ui 样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!