Material UI 以更高的特异性覆盖样式

Material UI Overriding styles with increased specificity

如何覆盖具有高特异性的 class 的规则?

例如.MuiAccordionSummary-content.Mui-expandedclass中的AccordionSummary

const useStyles = makeStyles(() => ({
    expanded: {
        marginBottom: 0,
    },
}));

结合:

<AccordionSummary classes={{
    expanded: classes.expanded,
}}/>

已应用但被覆盖。

注意marginBottom: '0 !important' 可行,但感觉不是最佳解决方案。

您可以使用全局替代来更改 AccordionSummary 的默认页边距。但是,这会影响应用程序中的所有 AccordionSummary 组件。

更好的方法(您已经在使用的方法)是包装组件并更改其 类。如果查看 AccordionSummary 的源代码,您会发现 expanded 属性 是一个空块。边距由 content 属性:

中的引用选择器设置
    content: {
      display: 'flex',
      flexGrow: 1,
      transition: theme.transitions.create(['margin'], transition),
      margin: '12px 0',
      '&$expanded': {
        margin: '20px 0',
      },
    },

如果您在自定义样式中添加相同的引用,则优先级会更高,您将不需要!important。不过,您必须将 expanded className 添加到您的自定义样式中:

import React from 'react';
import makeStyles from '@material-ui/core/styles/makeStyles'
import Accordion from '@material-ui/core/Accordion';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import AccordionSummary from '@material-ui/core/AccordionSummary';

const useStyles = makeStyles(() => ({
  expanded: {},
  content: {
    '&$expanded': {
      marginBottom: 0,
    },
  },
}));

const MyAccordion = ({ summary, details }) => {
  const classes = useStyles();

  return (
    <Accordion>
      <AccordionSummary classes={{ content: classes.content, expanded: classes.expanded }}>
        {summary}
      </AccordionSummary>
      <AccordionDetails>
        {details}
      </AccordionDetails>
    </Accordion>
  )
};

export default MyAccordion;