【发布时间】:2023-04-05 22:29:01
【问题描述】:
我尝试使用类名创建剪辑到页面顶部的 AppBar 并使用 React Hooks 和 Material Ui 悬停在其他 Drawer 上。全部描述在:https://material-ui.com/demos/drawers/#clipped-under-the-app-bar
所以我们有
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',
},
},
}));
还有更详细的:
<div className={classes.root}>
<CssBaseline/>
<LoadingResults showLoading={showLoadingSpinner}/>
<AppBar position="fixed" className={classes.appBar} >
...
</AppBar>
....
问题是使用 className 应用的样式是在元素的最后添加的,因此它不会覆盖原始样式:
class="MuiPaper-root-12 MuiPaper-elevation4-18 MuiAppBar-root-3 MuiAppBar-positionFixed-4 MuiAppBar-colorPrimary-10 mui-fixed Hook-appBar-1b6f20g"
我知道我可以使用内联样式,但想知道我是否可以使用带有钩子的 classNames 来覆盖样式,就像使用“传统”组件方法一样?
这里是沙盒:https://codesandbox.io/s/w7njqorzy7?fontsize=14
发生的情况是,在沙盒中代码可以正常工作(左侧容器上方的应用栏)
查看调试器,样式是内联的。 在沙盒中,钩子位于底部:
在浏览器中,当应用程序通过“运行开始”运行时,它位于顶部:
所以这就是区别,但为什么以及如何解决这个问题?
【问题讨论】:
-
class属性中的类顺序与生成的样式无关。重要的顺序是 CSS 类定义出现的顺序(例如样式元素的顺序<style>...</style>)。请显示重现您遇到的问题的 CodeSandbox。 -
我已经用沙盒更新了它。事实证明它在沙盒中的工作方式不同,而不是。
-
要使用
@material-ui/styles,您需要执行引导步骤(material-ui.com/css-in-js/basics/…) -
谢谢@JoshWooding。我安装了这个带有新样式的引导文件,但你的评论让我再次研究它。原来它是在material ui组件之后导入的,应该是第一件事。
标签: css reactjs material-ui react-hooks