programing

MUI 스타일을 사용하여 부모 위로 이동할 때 자녀의 스타일을 어떻게 변경합니까?

golfzon 2023. 3. 10. 23:01
반응형

MUI 스타일을 사용하여 부모 위로 이동할 때 자녀의 스타일을 어떻게 변경합니까?

반응으로 MUI를 사용하고 있어요예를 들어 다음과 같은 스타일의 컴포넌트가 있다고 합시다.

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

스타일을 바꾸고 싶다addIcon상공을 맴돌고 있을 때outerDiv위의 스타일을 사용합니다.

여기 제 예가 있습니다.

다음은 v4의 올바른 구문 예입니다( )."& $addIcon"안에 내포된.&:hover아래는 v5의 예입니다.

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

eager-tesla-xw2cg 편집

관련 문서 및 답변:


Material-UI v5를 처음 사용하기 시작한 사용자를 위해 아래 예에서는 동일한 스타일을 구현하지만 새로운 스타일을 활용합니다.sx소품

import Grid from "@mui/material/Grid";
import { useTheme } from "@mui/material/styles";
import AddIcon from "@mui/icons-material/Add";

export default function App() {
  const theme = useTheme();
  return (
    <Grid container>
      <Grid
        item
        sx={{
          p: 4,
          backgroundColor: theme.palette.grey[200],
          "&:hover": {
            backgroundColor: theme.palette.grey[100],
            cursor: "pointer",
            "& .addIcon": {
              color: "purple"
            }
          }
        }}
      >
        <AddIcon
          className="addIcon"
          sx={{
            height: "50px",
            width: "50px",
            color: theme.palette.grey[400],
            mb: 2
          }}
        />
      </Grid>
    </Grid>
  );
}

상위 위로 마우스 포인터 편집


여기 또 다른 v5의 예가 있는데, Emotion's를styledMaterial-UI가 아닌 기능sx소품:

import Grid from "@mui/material/Grid";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import AddIcon from "@mui/icons-material/Add";
import styled from "@emotion/styled/macro";

const StyledAddIcon = styled(AddIcon)(({ theme }) => ({
  height: "50px",
  width: "50px",
  color: theme.palette.grey[400],
  marginBottom: theme.spacing(2)
}));
const StyledGrid = styled(Grid)(({ theme }) => ({
  padding: theme.spacing(4),
  backgroundColor: theme.palette.grey[200],
  "&:hover": {
    backgroundColor: theme.palette.grey[100],
    cursor: "pointer",
    [`${StyledAddIcon}`]: {
      color: "purple"
    }
  }
}));
const theme = createTheme();
export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <Grid container>
        <StyledGrid item>
          <StyledAddIcon />
        </StyledGrid>
      </Grid>
    </ThemeProvider>
  );
}

상위 위로 마우스 포인터 편집


또한 Emotion의 css 프로포트를 사용한 v5의 예를 하나 더 소개합니다.

/** @jsxImportSource @emotion/react */
import Grid from "@mui/material/Grid";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import AddIcon from "@mui/icons-material/Add";

const theme = createTheme();
export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <Grid container>
        <Grid
          item
          css={(theme) => ({
            padding: theme.spacing(4),
            backgroundColor: theme.palette.grey[200],
            "&:hover": {
              backgroundColor: theme.palette.grey[100],
              cursor: "pointer",
              "& .addIcon": {
                color: "purple"
              }
            }
          })}
        >
          <AddIcon
            className="addIcon"
            css={(theme) => ({
              height: "50px",
              width: "50px",
              color: theme.palette.grey[400],
              marginBottom: theme.spacing(2)
            })}
          />
        </Grid>
      </Grid>
    </ThemeProvider>
  );
}

상위 위로 마우스 포인터 편집

이것은 부모 컴포넌트인 전류 셀렉터를 나타냅니다.

'&': { /* styles */ }

즉, 부모 컴포넌트가 호버 상태임을 의미합니다.

'&:hover': { /* styles */ }

즉, 부모 내부의 하위 구성 요소가 호버 상태에 있음을 의미합니다.

'&:hover .child': { /* styles */ }

앰퍼샌드를 생략할 수도 있습니다.&유사 클래스를 사용하는 경우:

':hover .child': { /* styles */ }

다음을 사용하여 코드를 완성합니다.sxprop (같은 스타일의 오브젝트를 사용할 수도 있습니다.styled()):

<Box
  sx={{
    width: 300,
    height: 300,
    backgroundColor: "darkblue",
    ":hover .child": {
      backgroundColor: "orange"
    }
  }}
>
  <Box className="child" sx={{ width: 200, height: 200 }} />
</Box>

Codesandbox 데모

아마도 분명한 점이지만, 위의 답변에 덧붙이자면, 별도의 className을 참조하는 경우 makeStyles 훅에서도 className을 생성해야 합니다.그렇지 않으면 작동하지 않습니다.예:

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

를 사용하고 있는 경우makeStylesMUI v4에서 MUI v5로 이행한 경우, 현재 Import하고 있는 경우makeStyles부터tss-react이 경우 다음 방법으로 동일한 결과를 얻을 수 있습니다.

import { makeStyles } from 'tss-react';

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

세 번째 인수는 에 전달되었습니다.makeStylescallback은 class 객체입니다.

언급URL : https://stackoverflow.com/questions/59178802/how-do-you-change-a-style-of-a-child-when-hovering-over-a-parent-using-mui-style

반응형