下面是一个示例,展示了在makeStyles 中指定媒体查询的两种方式(下面是使用styled 的v5 示例)。您可以使用theme.breakpoints中的up、down、only和between函数(根据主题中指定的断点为您生成媒体查询字符串),也可以直接使用媒体查询.
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,以匹配v5 中lg 断点的新值。
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