如何在 Reactjs Material UI 上使用 CSS @media

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 响应式?


白衣染霜花
浏览 54回答 1
1回答

小唯快跑啊

下面是一个示例,显示了在其中指定媒体查询的两种方法makeStyles(下面是使用 的 v5 示例styled)。您可以在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 的类似示例。这已调整为 usestyled而不是 ,并且和makeStyles的用法已根据这些函数的行为变化进行了调整(现在不包含指定的断点而不是包含,并且结束断点现在也是独占的,因此对于指定的断点需要比 v4 中使用的断点大一)。此外,直接指定的媒体查询的 已从 调整为 ,以匹配v5 中断点的新值。theme.breakpoints.downtheme.breakpoints.betweendownbetweenmin-width1280px1200pxlgimport 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>;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5