如何使用 CSS @media 在 Reactjs Material UI 上使用 makeStyles 进行响应?

IT技术 javascript html css reactjs material-ui
2021-04-18 20:16:51
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 响应?

1个回答

下面是一个示例,显示了在其中指定媒体查询的两种方法makeStyles(再往下是使用 的 v5 示例styled)。您可以使用updownonly,和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直接指定的媒体查询的 已从 调整1280px1200px以匹配lgv5 中断点的新值

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

在上面我的代码中,我将 makeStyles 用于按钮样式。但这似乎很复杂。我不知道为什么我必须使用 MakeStyles。如果你让我清楚这一点,我很感激。
2021-05-22 20:16:51
你能帮我另一个问题吗?如何使用 Box、Paper、Grid、Container... 使像素完美设计?对于像素完美,我必须使用我的自定义 CSS 吗?作为职业的最佳方式是什么?我也是前端开发人员,熟悉 HTML5、CSS3、Sass 和 Webpack。但我是 ReactJS 的新手。
2021-06-06 20:16:51
您不必使用“makeStyles”。如何管理 CSS 有很多选择,这就是其中之一。选择样式方法比我在评论中涵盖的内容要大得多。
2021-06-18 20:16:51
我不确定你所说的“像素完美”是什么意思,但如果你知道如何用 HTML5 和 CSS3 做到这一点,那么你可以用 React 做同样的事情。只是生成 HTML 和 CSS 的机制不同。
2021-06-19 20:16:51