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

前端 未结 1 906
悲&欢浪女
悲&欢浪女 2020-11-27 20:34

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

const useStyles = makeStyles(theme => ({
  outerDiv: {
    backgroundC         


        
相关标签:
1条回答
  • 2020-11-27 21:06

    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 and answers:

    • https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet
    • how to use css in JS for nested hover styles, Material UI
    • Material UI: affect children based on class
    • Advanced styling in material-ui
    0 讨论(0)
提交回复
热议问题