javascript - 在 Material ui 中使用 useMediaQuery?

标签 javascript reactjs material-ui

因此,在构建完整的 Web 应用程序之后,我决定使其适合移动设备。我正在使用带有反应的 Material ui 框架。我阅读了文档,但不确定 2 如何使用它。因此,让我概述一下我认为如何工作

假设我有这个组件

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

因此,如果我想根据断点(在本例中为“sm”)将样式应用于按钮,我会这样做:

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

假设我已经定义了 mobileBtndesktopBtn

这是使用它的正确方法,还是有其他一些标准方法可以这样做。虽然我不认为有,因为如果有它会包含在文档中。

最佳答案

如果我正确理解你的问题,有一个 built-in breakpoints mechanizmmakeStyles 中,因此如果您只想更改样式,则不需要 useMediaQuery

例如:

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

关于javascript - 在 Material ui 中使用 useMediaQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67352225/

相关文章:

javascript - 如何使用 Cocos2D-JS 将变量保存到 Android?

javascript - 如何从类渲染方法中提取 JSX?

reactjs - 如何在 Material ui datepicker React 中获取唯一日期?

javascript - Mysql Node.js 间歇性连接问题

javascript - HtmlUnit JavaScript : Cannot read property "style" from null

javascript - 如何将 mobx 与 React Rails 结合使用?

javascript - 具有 scss 的 node_module 上出现 Gulp 错误

javascript - [REACT]Material-ui 多个snackbar

reactjs - Jest : Cannot read property 'secondary' of undefined - after MUI upgrade from V4 toV5

javascript - ScrollView snapToInterval 和 snapToAlignment 不适用于文本元素列表