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);
관련 문서 및 답변:
- https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet
- 내포된 호버 스타일을 위해 JS에서 css를 사용하는 방법, 재료 UI
- 머티리얼 UI: 클래스에 따라 아이에게 영향을 줍니다.
- 소재의 고급 스타일링
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>
아마도 분명한 점이지만, 위의 답변에 덧붙이자면, 별도의 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
'programing' 카테고리의 다른 글
| 여러 모델 서브클래스의 Backbone.js 컬렉션 (0) | 2023.03.10 |
|---|---|
| React/J에서 물결 괄호를 일반 텍스트로 렌더링SX (0) | 2023.03.10 |
| 주 클래스 org.apache.maven을 찾거나 로드할 수 없습니다.랩퍼메이븐 래퍼 메인 (0) | 2023.03.10 |
| ngRepeat 사용 시 표시되는 결과 수 제한 (0) | 2023.03.10 |
| wp-config.php에서 값(PHP 정의 상수)을 읽으려면 어떻게 해야 하나요? (0) | 2023.03.10 |