How do you change a style of a child when hovering over a parent using material-ui jss styles

淺唱寂寞╮ 提交于 2019-12-22 10:51:56

问题


I'm using material-ui in react. Let's say I have this component with these styles

const useStyles = makeStyles(theme => ({
  outerDiv: {
    backgroundColor: theme.palette.grey[200],
    padding: theme.spacing(4),
    '&:hover': {
      cursor: 'pointer',
      backgroundColor: theme.palette.grey[100]
   }
  },
  addIcon: (props: { dragActive: boolean }) => ({
    height: 50,
    width: 50,
    color: theme.palette.grey[400],
    marginBottom: theme.spacing(2)
  })
}));

function App() {
  const classes = useStyles();
  return (
    <Grid container>
      <Grid item className={classes.outerDiv}>
        <AddIcon className={classes.addIcon} />
      </Grid>
    </Grid>
  );
}

I want to change the style of addIcon when hovering over outerDiv using the styles above.

Here's my example: https://codesandbox.io/s/trusting-mcnulty-b1gcd?fontsize=14&hidenavigation=1&theme=dark


回答1:


Below is an example of the correct syntax ("& $addIcon" nested within &:hover).

import * as React from "react";
import { render } from "react-dom";
import { Grid, makeStyles } from "@material-ui/core";
import AddIcon from "@material-ui/icons/Add";

const useStyles = makeStyles(theme => ({
  outerDiv: {
    backgroundColor: theme.palette.grey[200],
    padding: theme.spacing(4),
    '&:hover': {
      cursor: 'pointer',
      backgroundColor: theme.palette.grey[100],
      "& $addIcon": {
        color: "purple"
      }
   }
  },
  addIcon: (props: { dragActive: boolean }) => ({
    height: 50,
    width: 50,
    color: theme.palette.grey[400],
    marginBottom: theme.spacing(2)
  })
}));

function App() {
  const classes = useStyles();
  return (
    <Grid container>
      <Grid item className={classes.outerDiv}>
        <AddIcon className={classes.addIcon} />
      </Grid>
    </Grid>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

Related documentation:

  • https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet


来源:https://stackoverflow.com/questions/59178802/how-do-you-change-a-style-of-a-child-when-hovering-over-a-parent-using-material

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!