材质ui中的目标伪选择器

时间:2020-06-16 18:50:09

标签: css-selectors material-ui

我想知道是否有一种方法可以在材料ui中定位psedo选择器(::before, ::after)? 例如,在这样的组件中?

const useStyles = makeStyles((theme) => ({
  root: {
    textAlign: 'center',
    '&::before': {
      content: '"blabla"'
    },
    '&::after': {
      content: '"blabla"'
    },
    ':before': {},
    after: {}
  }
}));

function App(props) {
  const classes = useStyles();
  return (
    <Typography
      className={{ root: classes.root, before: classes.before, after: classes.after }}>
      {props.children}
    </Typography>
  );
}

1 个答案:

答案 0 :(得分:1)

我已经创建了this sandbox project,您可以检查它是否运行正常,或者如果我缺少一些可以理解您的问题的信息,可以纠正我的问题

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";

const useStyles = makeStyles(theme => ({
  root: {
    textAlign: "center",
    "&::before": {
      content: '"-"'
    },
    "&::after": {
      content: '"-"'
    }
  }
}));

export default function App(props) {
  const classes = useStyles();
  return (
    <Typography className={classes.root} {...props}>
      Hello
    </Typography>
  );
}

我认为您使用className道具的方式错误,您必须传递字符串,而不是对象。 classes道具需要一个对象,我们通常在组件上使用暴露了类名的类道具以覆盖其内部样式,例如,在Typography组件的情况下,您可以像这样覆盖根元素样式。 / p>

export default function App(props) {
  const classes = useStyles();
  return (
    <Typography classes={{ root: classes.root }} {...props}>
      Hello
    </Typography>
  );
}

因此classesclassNames在Material-UI中是两件事,但是有时(当您想将样式应用于组件的根元素时)两者都提供相同的解决方案。

我用第二种解决方案又创建了一个Sandbox project