且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

material-ui makeStyles:如何通过标签名称设置样式?

更新时间:2022-12-17 08:25:25

由于您希望将此范围限定于组件,因此需要一个类来应用于您的组件(例如,示例中的 classes.root 以下).然后,您可以使用&定位其中的所有 p 元素.p .如果您随后需要为组件中的另一个CSS类覆盖 p 标记样式,则可以使用另一个嵌套规则来定位也具有该类的 p 标记(例如 classes.title ).

Since you want this scoped to your component, you need a class to apply to your component (e.g. classes.root in the example below). Then you can target all p elements within that using & p. If you then need to override the p tag styling for another CSS class within your component, you can use another nested rule to target p tags that also have that class (e.g. classes.title in the example).

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

const useStyles = makeStyles(theme => ({
  root: {
    "& p": {
      margin: 0,
      "&$title": {
        margin: "0 0 16px"
      }
    }
  },
  title: {}
}));
export default function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <p>This paragraph isn't affected.</p>
      <p>This paragraph isn't affected.</p>
      <div className={classes.root}>
        <p className={classes.title}>My title</p>
        <p>A paragraph</p>
        <p>Another paragraph</p>
      </div>
    </div>
  );
}

相关文档: https://cssinjs.org/jss-plugin-nested?v=v10.1.1#use--to-reference-selector-the-parent-rule