带有 MUI 的 CSS 伪选择器

IT技术 reactjs material-ui jss
2021-04-11 17:07:48

我在很多 MUI 代码中看到,他们在 React 样式的组件中使用了伪选择器。我以为我会尝试自己做,但我无法让它发挥作用。我不确定我做错了什么,或者这是否可能。

我正在尝试制作一些 CSS 来抵消这个元素对固定标题的影响。

import React from 'react';
import { createStyles, WithStyles, withStyles, Typography } from '@material-ui/core';
import { TypographyProps } from '@material-ui/core/Typography';
import GithubSlugger from 'github-slugger';
import Link from './link';

const styles = () =>
  createStyles({
    h: {
      '&::before': {
        content: 'some content',
        display: 'block',
        height: 60,
        marginTop: -60
      }
    }
  });

interface Props extends WithStyles<typeof styles>, TypographyProps {
  children: string;
}

const AutolinkHeader = ({ classes, children, variant }: Props) => {
  // I have to call new slugger here otherwise on a re-render it will append a 1
  const slug = new GithubSlugger().slug(children);

  return (
    <Link to={`#${slug}`}>
      <Typography classes={{ root: classes.h }} id={slug} variant={variant} children={children} />
    </Link>
  );
};

export default withStyles(styles)(AutolinkHeader);
2个回答

我发现内容属性需要像这样双引号

const styles = () =>
  createStyles({
    h: {
      '&::before': {
        content: '"some content"',
        display: 'block',
        height: 60,
        marginTop: -60
      }
    }
  });

然后一切都按预期进行

好吧,内容浪费了我的时间。
2021-05-25 17:07:48
内容:'“一些内容”',您错过了封闭式报价,但无论如何谢谢,您救了我的一天。
2021-05-29 17:07:48
谢谢。你救了我的一天。
2021-05-29 17:07:48
浪费了2个小时。我正在使用内容:'blabla'但它不起作用🤦‍♂️
2021-06-17 17:07:48
这对于空的伪元素也很重要。IEcontent: '""'
2021-06-18 17:07:48

正如@Eran Goldin 所说,检查您的content财产的value并确保将其设置为 string ""很可能,你正在做这样的事情:

'&::before': {
  content: '',
  ...
}

content在输出样式表中根本没有设置属性

.makeStyles-content-154:before {
  content: ;
  ...
}

在 Material-UI 样式对象中,字符串的内容是 css 值,包括双引号,修复它简单地写

'&::before': {
  content: '""', // "''" will also work.
  ...
}