【问题标题】:How can I use CSS @media for responsive with makeStyles on Reactjs Material UI?如何在 Reactjs Material UI 上使用 CSS @media 响应 makeStyles?
【发布时间】:2020-07-15 13:37:38
【问题描述】:
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 响应?

【问题讨论】:

标签: javascript html css reactjs material-ui


【解决方案1】:

下面是一个示例,展示了在makeStyles 中指定媒体查询的两种方式(下面是使用styled 的v5 示例)。您可以使用theme.breakpoints中的updownonlybetween函数(根据主题中指定的断点为您生成媒体查询字符串),也可以直接使用媒体查询.

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.downtheme.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

【讨论】:

  • 你能帮我解决另一个问题吗?如何使用 Box、Paper、Grid、Container... 使像素完美设计?为了像素完美,我必须使用我的自定义 CSS 吗?什么是看待职业的最佳方式?我也是前端开发人员,非常了解 HTML5、CSS3、Sass 和 Webpack。但我是 ReactJS 的新手。
  • 我不确定你所说的“像素完美”是什么意思,但如果你知道如何使用 HTML5 和 CSS3 来做到这一点,那么你可以使用 React 来做同样的事情。只是生成 HTML 和 CSS 的机制不同。
  • 在上面我的代码中,我使用 makeStyles 作为按钮样式。但这似乎很复杂。我不知道为什么我必须使用 MakeStyles。如果你让我明白这一点,我很感激。
  • 您不必使用“makeStyles”。如何管理 CSS 有很多选择,这就是其中之一。选择一种样式方法是一个比我在 cmets 中所能涵盖的更大的话题。
猜你喜欢
  • 1970-01-01
  • 2022-01-06
  • 2020-04-01
  • 1970-01-01
  • 2018-04-29
  • 2021-03-24
  • 2022-01-09
  • 1970-01-01
  • 2019-02-02
相关资源
最近更新 更多