使用material-ui jss样式将鼠标悬停在父项上时如何更改子项的样式

时间:2019-12-04 14:54:01

标签: reactjs css-selectors material-ui jss onhover

我在反应中使用了Material-ui。假设我有这些样式的组件

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>
  );
}

当我使用上面的样式将鼠标悬停在outsideDiv上时,我想更改addIcon的样式。

这是我的示例:https://codesandbox.io/s/trusting-mcnulty-b1gcd?fontsize=14&hidenavigation=1&theme=dark

2 个答案:

答案 0 :(得分:2)

下面是正确语法的示例("& $addIcon"嵌套在&: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);

Edit eager-tesla-xw2cg

相关文档:

答案 1 :(得分:0)

这可能是一个显而易见的观点,但只是为了补充上面的答案:如果您正在引用一个单独的 className,请不要忘记您还需要在 makeStyles 钩子中创建它,否则它将无法工作。例如:

const useStyles = makeStyles({
  parent: {
    color: "red",
    "&:hover": {
      "& $child": {
        color: "blue" // will only apply if the class below is declared (can be declared empty)
      }
    }
  },
  // child: {} // THIS must be created / uncommented in order for the code above to work; assigning the className to the component alone won't work.
})

const Example = () => {
  const classes = useStyles()
  return (
    <Box className={classes.parent}>
      <Box className={classes.child}>
        I am red unless you create the child class in the hook
      </Box>
    </Box>
  )
}