为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白衣染霜花 2023-10-30 15:59:41
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 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

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


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>;

}


查看完整回答
反对 回复 2023-10-30
  • 1 回答
  • 0 关注
  • 51 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信