JSS样式定义中的目标嵌套材料组件

时间:2020-06-22 12:30:35

标签: reactjs material-ui jss

我目前有这个JSX布局

<div className={classes.bottomArea}>
    <Box display="flex" flexDirection="column">
        <Typography variant="h1" component="span">1982</Typography>
        <Typography variant="h5" component="span">Bed Count</Typography>
    </Box>
</div>

在我的样式中,我试图更改h5版式元素的颜色

bottomArea: {
    $h5: {
        color: "red"
    }
}

我想我理解为什么这不起作用,但是有一种简单的方法来定位该h5变体吗?

这是要显示的代码框

like here

3 个答案:

答案 0 :(得分:0)

您使用Typography道具的方式错误。 variant道具仅定义应用于组件的样式,而component道具定义将使用哪个标签渲染该组件。

如果您希望Typography组件为h5

<Typography variant="h5" component="h5">Bed Count</Typography>

然后进行样式设置:

bottomArea: {
    '& h5': {
        color: "red"
    }
}

CodeSanbox:https://codesandbox.io/s/material-demo-6i1lq?file=/demo.js

美好的一天!

答案 1 :(得分:0)

您可以使用withStyle更新特定的组件类

选中此Typography API

const Typography = withStyles(() => ({
  h5: {
    color: "red",
  },
}))(MuiTypography);

export default function Types() {
  return (
    <div>
      <Box display="flex" flexDirection="column">
        <Typography variant="h1" component="span">
          1982
        </Typography>
        <Typography variant="h5" component="span">
          Bed Count
        </Typography>
      </Box>
    </div>
  );
}

Edit Material demo

答案 2 :(得分:0)

假设您想保留<span>作为组件,则可以通过定位h5添加的CSS类Typography来定位MuiTypography-h5变体。

在下面显示的语法中,&指为bottomArea生成的类,然后空格指示将.MuiTypography-h5定位为descendant

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

const useStyles = makeStyles({
  bottomArea: {
    "& .MuiTypography-h5": {
      color: "red"
    }
  }
});

export default function Types() {
  const classes = useStyles();

  return (
    <div className={classes.bottomArea}>
      <Box display="flex" flexDirection="column">
        <Typography variant="h1" component="span">
          1982
        </Typography>
        <Typography variant="h5" component="span">
          Bed Count
        </Typography>
      </Box>
    </div>
  );
}

Edit Target nested typography by variant

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

相关答案:How do you change a style of a child when hovering over a parent using material-ui jss styles