如何在React中添加媒体查询?

时间:2020-06-07 05:57:12

标签: javascript reactjs responsive-design material-ui material-design

能否请您告诉我如何在材料界面中添加媒体查询? 我检查了此链接

ReactJS: Material ui breakpoints

提到down函数用于max-width,而up的意思是min-width

https://codesandbox.io/s/fervent-meitner-iyu90?file=/src/App.js

 const matches = useMediaQuery(theme.breakpoints.down("sm"));
  console.log(matches);

材料界面具有以下断点

xs (extra-small): 0px or larger
sm (small): 600px or larger
md (medium): 960px or larger
lg (large): 1280px or larger
xl (extra-large): 1920px or larger

为什么没有给我期望的输出??

此行useMediaQuery(theme.breakpoints.down("sm"));的宽度应小于true时应给600px,但它给我错误的输出,为什么?

当前,当宽度小于true时,输出为960;当宽度大于false时,输出为960

2 个答案:

答案 0 :(得分:0)

您需要像这样将应用程序包装在ThemeProvider中,并将down替换为up

import React from "react";
import ReactDOM from "react-dom";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";

import App from "./App";

    const theme = createMuiTheme();

    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <React.StrictMode>
        <ThemeProvider theme={theme}>
          <App />
        </ThemeProvider>
      </React.StrictMode>,
      rootElement
    );

此处是完整的有效链接codeSandbox

答案 1 :(得分:-1)

在react中使用样式化的组件,您可以添加

从“样式化的组件”导入样式;

export const OutterListWrapper = styled.div`
@media screen and (min-width: 300px) and (max-width: 400px) {
top: -40px !important;
}
`;