符号 &tagname 的含义:用于 material UI 中的 css 样式。例如:&div: { 显示:'flex' '}

What is meaning of symbol &tagname: for css styling in material UI. Ex: &div: { display: 'flex' '}

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

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

下面是使用 class 的代码片段。

 <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>

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

The ampersand (&) can be used to refer back to the main component.

Ampersands (&) get replaced by our generated, unique classname for that styled component, making it easy to have complex logic.

参见 Material-UI 的 Nesting Selectors 演示。

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>
  );
}

&div 将样式应用于 contactWrapper class 内的 <div> 标签。 这是 material UI 的做法 Selector nesting