【问题标题】:How override material ui style with hooks如何用钩子覆盖材质 ui 样式
【发布时间】: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 类定义出现的顺序(例如样式元素的顺序 &lt;style&gt;...&lt;/style&gt;)。请显示重现您遇到的问题的 CodeSandbox。
  • 我已经用沙盒更新了它。事实证明它在沙盒中的工作方式不同,而不是。
  • 要使用@material-ui/styles,您需要执行引导步骤(material-ui.com/css-in-js/basics/…)
  • 谢谢@JoshWooding。我安装了这个带有新样式的引导文件,但你的评论让我再次研究它。原来它是在material ui组件之后导入的,应该是第一件事。

标签: css reactjs material-ui react-hooks


【解决方案1】:

原来我安装新样式的 bootstrap.js 放错地方了。

import { install } from '@material-ui/styles';

install();

应该在导入任何材质ui组件之前执行。

【讨论】:

    【解决方案2】:

    您可以使用 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/

    【讨论】:

    • 第一个网址坏了
    【解决方案3】:

    https://material-ui.com/ru/styles/advanced/#makestyles

    const useStyles = makeStyles({
      root: {}, // a style rule
      label: {}, // a nested style rule
    });
    
    function Nested(props) {
      const classes = useStyles(props);
      return (
        <button className={classes.root}>
          <span className={classes.label}> // 'jss2 my-label'
            nested
          </span>
        </button>
      );
    }
    
    function Parent() {
      return <Nested classes={{ label: 'my-label' }} />
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2019-02-22
      • 2021-05-11
      • 2017-09-27
      • 1970-01-01
      • 2020-08-19
      • 2020-07-24
      相关资源
      最近更新 更多