const useStyles = makeStyles(theme => ({
wrapper: {
width: "300px"
},
text: {
width: "100%"
},
button: {
width: "100%",
marginTop: theme.spacing(1)
},
select: {
width: "100%",
marginTop: theme.spacing(1)
}
}));
有没有办法在上述变量中使用 CSS @media?
如果不可能,我怎样才能使我的自定义 css 响应?
最佳答案
下面的示例显示了在 makeStyles
中指定媒体查询的两种方法。 (下面是使用 styled
的 v5 示例)。您可以使用 up
, down
, only
, 和 between
theme.breakpoints 中的函数(根据主题中指定的断点为您生成媒体查询字符串),或者您可以直接使用媒体查询。
import React from "react";
import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
button: {
color: "white",
[theme.breakpoints.down("xs")]: {
marginTop: theme.spacing(1),
backgroundColor: "purple"
},
[theme.breakpoints.between("sm", "md")]: {
marginTop: theme.spacing(3),
backgroundColor: "blue"
},
"@media (min-width: 1280px)": {
marginTop: theme.spacing(5),
backgroundColor: "red"
}
}
}));
export default function App() {
const classes = useStyles();
return (
<Button className={classes.button} variant="contained">
Hello World!
</Button>
);
}
相关文档:
下面是一个使用 Material-UI v5 的类似示例。这已被调整为使用
styled
而不是 makeStyles
以及 theme.breakpoints.down
的用法和 theme.breakpoints.between
已根据这些函数的行为变化进行了调整(down
现在不包含指定的断点而不是包含的断点,并且 between
的结束断点现在也是不包含的,因此对于这两个断点都需要指定比 v4 中使用的内容更上一层楼)。此外,min-width
直接指定的媒体查询的数量已从 1280px
调整至1200px
匹配 lg
的新值v5 中的断点。import React from "react";
import Button from "@material-ui/core/Button";
import { styled } from "@material-ui/core/styles";
const StyledButton = styled(Button)(({ theme }) => ({
color: "white",
[theme.breakpoints.down("sm")]: {
marginTop: theme.spacing(1),
backgroundColor: "purple"
},
[theme.breakpoints.between("sm", "lg")]: {
marginTop: theme.spacing(3),
backgroundColor: "blue"
},
"@media (min-width: 1200px)": {
marginTop: theme.spacing(5),
backgroundColor: "red"
}
}));
export default function App() {
return <StyledButton variant="contained">Hello World!</StyledButton>;
}
从 v4 到 v5 的断点更改文档:https://next.material-ui.com/guides/migration-v4/#theme
关于javascript - 如何在 Reactjs Material UI 上使用 CSS @media 响应 makeStyles?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61010951/