【问题标题】:material-ui makeStyles: how to style by tag name?material-ui makeStyles:如何按标签名称设置样式?
【发布时间】:2020-08-04 07:22:34
【问题描述】:

我想为当前组件中的所有<p> 添加规则。我在任何地方都找不到有关如何按标签名称添加 CSS 规则的信息(material-ui 文档、Stack Overflow 等)。

不支持吗?

我正在尝试做这样的事情:

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        'p': {
            margin: 0,
        },
        someClass: {
            fontSize: 14,
        },
    })
);

编辑:

使用 Ryan 的解决方案有效,但产生了一个新问题:

import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core';

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        root: {
            '& p': {
                margin: 0,
            },
        },
        // I want this rule to override the rule above. It's not possible in the current configuration, because `.root p` is more specific than `.title`
        // This problem originates from the fact that I had to nest the rule for `<p>` inside a CSS class
        title: {
            margin: '0 0 16px',
        },
    })
);

export default () => {
    const classes = useStyles({});

    return (
        <div className={classes.root}>
            <p className={classes.title}>My title</p>
            <p>A paragraph</p>
            <p>Another paragraph</p>
        </div>
    );
};

【问题讨论】:

  • 你可以在你的项目中添加一个css文件并像import 'style.css'一样导入

标签: javascript reactjs material-ui jss


【解决方案1】:

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

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-of-the-parent-rule

【讨论】:

  • 行得通,谢谢!不幸的是,现在我遇到了一个新问题:.someClass p 的规则过于具体,这意味着它会覆盖此 createStyles 对象中的其他样式
  • @LiranH 请在您问题的代码中显示其他样式。
猜你喜欢
  • 2019-01-05
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 2020-01-01
相关资源
最近更新 更多