符号 '&$checked' 的含义是什么?

14
import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import { createMuiTheme, makeStyles, ThemeProvider } from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';

const useStyles = makeStyles(theme => ({
  root: {
    color: theme.status.danger,
    '&$checked': {
      color: theme.status.danger,
    },
  },
  checked: {},
}));

function CustomCheckbox() {
  const classes = useStyles();

  return (
    <Checkbox
      defaultChecked
      classes={{
        root: classes.root,
        checked: classes.checked,
      }}
    />
  );
}

const theme = createMuiTheme({
  status: {
    danger: orange[500],
  },
});

export default function CustomStyles() {
  return (
    <ThemeProvider theme={theme}>
      <CustomCheckbox />
    </ThemeProvider>
  );
}
这个 CodeSandbox 中使用的符号 '&$checked' 是什么意思?请详细解释每个符号的含义以及相关逻辑。
谢谢回答。
3个回答

18
&是对父规则(在本例中为“root”)的引用。$ruleName(其中“ruleName”在本例中为“checked”)是对同一样式表中局部规则的引用。
为了澄清上述术语,makeStyles的参数用于生成具有多个样式规则的样式表。每个对象键(例如“root”,“checked”)称为“规则名称”。当您调用useStyles时,生成的classes对象包含将每个规则名称映射到生成的CSS类名称的映射。
因此,在这种情况下,假设“root”的生成类名为“root-generated-1”,而“checked”的生成类名为“checked-generated-2”,那么&$checked等效于.root-generated-1.checked-generated-2,意味着它将匹配应用了rootchecked类的元素。
就复选框的影响而言,在处于“选中”状态时,Material-UI会将“checked”类应用于复选框。此样式规则覆盖了默认选中复选框的颜色(默认为主题中的次要颜色)。
相关答案和文档:
- https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use--to-reference-selector-of-the-parent-rule - https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet - React Material-UI中“makeStyles”的内部实现?

1
你的回答很棒。我还想问一下 '& $ checked' 中单引号的含义是什么。有没有相关文档?抱歉,也许我表达得太激动了。 - 6899 huge
单引号只是JavaScript中定义字符串的语法。 - Ryan Cogswell

1

'&$checked' 表示您可以在选中后覆盖元素。

在您的情况下,您正在覆盖复选框选中后的颜色

"&$checked": {
      color: theme.status.danger
    }

请查看附件以获取详细信息。

I've overridden the colour into the green after checked the box


-5
您可能指的是 .color>*:checked 元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接