如何使用钩子覆盖材料ui样式 [英] How override material ui style with hooks

查看:34
本文介绍了如何使用钩子覆盖材料ui样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建剪切到页面顶部的AppBar,并使用类名将其与React Hooks和Material Ui悬停在其他Drawer上.详情请参见:

但是当下载并编译相同的项目时,这是不可行的:

看一下调试器,样式是内联的.在沙盒中,挂钩位于底部:

在浏览器中,通过运行启动"运行应用时,其位于顶部:

这就是区别,但是为什么以及如何解决呢?

解决方案

您可以使用 classes 道具而不是 classNames 覆盖Material-ui样式.

例如

 < AppBar position ="fixed" classes = {{root:classes.appBar}}> 

在这里,我使用了 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆