简体   繁体   English

在材质ui中使用useMediaQuery?

[英]Using useMediaQuery in material ui?

So after building the complete web application, I've decided to make it mobile friendly.所以在构建了完整的 web 应用程序之后,我决定让它对移动设备友好。 I'm using material ui framework with react.我正在使用带有反应的材料 ui 框架。 I read the documentation but am not sure as 2 how to use it.我阅读了文档,但不确定 2 如何使用它。 So let me give you an overview of what I think how to work it所以让我给你一个概述,我认为如何工作

Say I have this component说我有这个组件

function App() {
  const matches = useMediaQuery(theme.breakpoints.down('sm'));
  return (
    <Button variant="contained" color="primary">
    </Button>
  );
}

So if I wanna apply styles to button as per the breakpoint(in this case 'sm'), I'd do something like this:因此,如果我想根据断点将 styles 应用于按钮(在本例中为“sm”),我会这样做:

...
<Button styles={{matches? mobileBtn : desktopBtn}}>
...

assumming I have defined mobileBtn and desktopBtn .假设我已经定义mobileBtndesktopBtn

Is this the correct approach to use it, or is there some other standard way to do so.这是使用它的正确方法,还是有其他标准方法可以这样做。 Although I don't think there is because if there was it would be included in the documentation.虽然我不认为有,因为如果有的话,它会包含在文档中。

If I understand your question correctly, there is a built-in breakpoints mechanizm in makeStyles so you don't need useMediaQuery if you only want to change styles.如果我正确理解您的问题, makeStyles中有一个内置的断点机制,因此如果您只想更改 styles,则不需要useMediaQuery

For example:例如:

const useStyles = makeStyles((theme) => ({
  button: {
    padding: 8,
    backgroundColor: 'green',

    [theme.breakpoints.down('sm')]: {
      backgroundColor: 'red'
    },
  },
}));

function App() {
  const classes = useStyles();
  return (
    <Button variant="contained" className={classes.button}>
      Hello World
    </Button>
  );
}

https://codesandbox.io/s/restless-night-4zn76?file=/index.jshttps://codesandbox.io/s/restless-night-4zn76?file=/index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM