首页 > 解决方案 > 符号 &tagname 的含义:用于材质 UI 中的 css 样式。例如:&div: { display: 'flex' '}

问题描述

我正在使用 React Material UI。符号&div:在组件的这个 CSS 样式中是什么意思。CSS样式如下。

  contactWrapper: {
    marginTop: theme.spacing(1),
    '& div': {
      display: 'flex',
    },
  },

下面是使用该类的代码片段。

 <div className={classes.contactWrapper}>
            <span className={classes.contentLabel}> Contact:</span>
            <div><Person className={classes.contactIcon} fontSize="small" /> {primaryContact.name}</div>
            <div><Phone className={classes.contactIcon} fontSize="small" /> {primaryContact.phone}</div>
          </div>
 </div>

标签: reactjsreact-material

解决方案


它是 Material-ui 的Styled-Components API的一部分。它是元素父类名的引用。

与号 (&) 可用于引用主要组件。

与符号 (&) 被我们为该样式组件生成的唯一类名所取代,从而使复杂逻辑变得容易。

请参阅 Material-UI 的嵌套选择器演示。

const useStyles = makeStyles({
  root: {
    color: 'red',
    '& p': { // p that is child of root classname
      margin: 0,
      color: 'green',
      '& span': { // span that is child of parent p
        color: 'blue',
      },
    },
  },
});

export default function NestedStylesHook() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      This is red since it is inside the root.
      <p>
        This is green since it is inside the paragraph{' '}
        <span>and this is blue since it is inside the span</span>
      </p>
    </div>
  );
}

推荐阅读