【问题标题】:Cant override styles of nested Material UI components无法覆盖嵌套 Material UI 组件的样式
【发布时间】:2021-01-11 05:06:49
【问题描述】:

我正在使用材质 ui 的 card 和 cardContent 组件。我在功能组件中都有,并且正在尝试覆盖每个组件的根样式。但是,我不知道如何修改 cardContent 组件的 css。通过修改card的根样式似乎是这样的。它不会让我修改 cardcomponent 的根样式。相反,我的 css 在检查器中显示为在

.jss14 {
    height: 100%;
    display: flex;
    padding: 0;
    flex-direction: column;
    justify-content: space-between;
}

而不是在.MuiCardContent-root

使用 makeStyles 有什么遗漏吗?

我的尝试

import React from "react"
import { makeStyles } from "@material-ui/core/styles"

import CardContent from "@material-ui/core/CardContent"

const useStyles = makeStyles({
  root: {
    display: "flex",
    justifyContent: "space-between",
    flexDirection: "column",
    height: "100%",
    padding: 0,
  },
})

export default function AccountCardContent(props) {
  const classes = useStyles()

  return <CardContent className={classes.root}> {props.children}</CardContent>
}

import React from "react"
import { makeStyles } from "@material-ui/core/styles"
import Card from "@material-ui/core/Card"

import AccountCardContent from "../AccountCardContent"

const useStyles = makeStyles({
  root: {
    width: "324px",
    height: "194px",
    borderRadius: "8px",
  },
})

export default function AccountCard({ icon, title, description, onClick }) {
  const classes = useStyles()

  return (
    <Card className={classes.root} onClick={onClick}>
      <AccountCardContent>asdf</AccountCardContent>
    </Card>
  )
}

【问题讨论】:

  • 另外,你可以选择你自己的名字,你不必命名为root
  • 感谢您查看 hotpink!因此,在您的示例中,当我使用检查器时,您的 hotpink cardContent 没有覆盖默认的padding-bottom: 24px。这正是我的问题。我不明白如何覆盖这个默认值。
  • 啊,我明白了,我只是添加了背景颜色来证明我的观点,而不是检查您的个人声明。我现在就给它一个正确的答案。

标签: javascript reactjs material-ui


【解决方案1】:

您的代码大部分是正确的,您的问题与 MUI 或 React 无关,而是CSS specificity。您正在尝试覆盖

.MuiCardContent-root:last-child

并且添加的伪类导致比您的.jss14(开发中的makeStyles-root-14)类更高的特异性。理想情况下,你总是模仿你试图覆盖的选择器,在这种情况下:

  root: {
    // other styles
    "&:last-child": {
      paddingBottom: 0
    }
  }

如果有疑问,您可以通过在选择器中添加额外的&amp; 来逐步增加特异性,直到它起作用:

  root: {
    // other styles
    "&&": {
      paddingBottom: 0
    }
  }

【讨论】:

    【解决方案2】:

    基本上,Material UI 组件接受一个classes 属性,可用于覆盖其样式。

    请查看here

    所以你可以这样做:

    <Card
      classes={{
        root: classes.root, // class name, e.g. `classes-nesting-root-x`
      }}
    >
    

    【讨论】:

    • 只要您只定位 root 而不是嵌套的子 className 就可以正常工作,如您提供的链接中所述。
    猜你喜欢
    • 2019-06-01
    • 2019-04-15
    • 2019-10-02
    • 2020-06-13
    • 2019-04-23
    • 2020-03-20
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多