簡體   English   中英

如何根據屏幕寬度 Material UI 更改間距系統?

[英]How to change spacing system based on screen width Material UI?

我有一個這樣的組件

<Box px={3}>
  <Content />
</Box>

其實這段代碼在移動端渲染的時候是沒有問題的。 但是當我的應用程序在桌面或更大的屏幕上呈現時,paddingX 仍然保持等於 24px(我使用 8 base - 8*3=24)。

P/s :我試圖修改 theme.js 中的 theme.spacing 但似乎是 Material UI 不允許我們根據斷點自定義間距。

所以我的問題是,如何根據屏幕寬度更改間距系統?

您不能更改每個斷點上的間距基值,但可以更改每個斷點上的間距乘數:

<Box px={{xs:1, sm:2, md:3}}>
  <Content />
</Box>

支持邊距和填充道具

自定義斷點值可以通過實現createMuiTheme來完成:

https://material-ui.com/customization/breakpoints/#custom-breakpoints

import { createMuiTheme } from '@material-ui/core/styles';
const theme = createMuiTheme(
   {breakpoints: {
    values: {
      xs: 0,
      sm: 600,
      md: 900,
      lg: 1200,
      xl: 1600,
    },
  })

看起來這還有待實施

rnanania建議的解決方法是根據斷點檢測有條件地設置間距:

import { useTheme } from '@material-ui/styles';

const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('xs'), {
  defaultMatches: true
});

<Grid container spacing={isMobile ? 0 : 4}>
</Grid>

您可以使用可以幫助您獲取寬度的 mediaQuery 鈎子,即 lg、md、sm,並在此基礎上您可以有條件地修改間距。

來源: 鏈接到帶有示例的文檔

嘗試反應設備檢測,它允許確定您正在運行代碼的設備並根據它創建特定行為

https://www.npmjs.com/package/react-device-detect

所以我試圖用 MUI 主題來獲得這個功能。 我希望 theme.spacing 將根據媒體查詢返回不同的數字。 這是我的解決方案。 這不是最好的,因為它不會對第一次渲染后的媒體查詢更改做出反應,但這對我有用。

覆蓋 theme.spacing 方法以獲得此功能:

const originalSpacing = theme.spacing;

function extractMediaQuery(fullMediaString /* shape of : '@media (min-    width:960px)' */) {
  const cutFromIndex = fullMediaString.indexOf('(');
  /* shape of : '(min-width:960px)' */
  return fullMediaString.substring(cutFromIndex);
}

const mediaQueriesStrings = {
  upMd: extractMediaQuery(theme.breakpoints.up('md')),
  smDown: extractMediaQuery(theme.breakpoints.down('sm')),
};

theme.spacing = (...args) => {
  if (window.matchMedia(mediaQueriesStrings.upMd).matches) {
    return originalSpacing(...args);
  }
// use the ratio you want. this will return 4 on mobile devices insted of 8 on desktop
  const relativeSpacing = args.map(spacing => spacing / 2);
  return originalSpacing(...relativeSpacing);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM