【问题标题】:How to set breakpoints when overriding theme variables in createMuiTheme在 createMuiTheme 中覆盖主题变量时如何设置断点
【发布时间】:2019-06-20 10:52:13
【问题描述】:

我正在尝试将默认主题排版字体大小设置为根据断点进行更改。例如,当断点位于 {xs} 值时,将 theme.typography.h4.fontSize 更改为 '1.5rem'。在所有其他断点处,将其保留为默认值 ('2.125rem')。

我可以使用以下代码示例在组件中轻松做到这一点:

const useStyles = makeStyles(theme => ({
    title: {
        [theme.breakpoints.down('xs')]: {
            fontSize: '1.5rem',
        }
    },
}))

但是,这意味着必须将相同的代码添加到每个包含 <Typography variant='h4'> 的组件中。如果我决定将值从 '1.5rem' 更改为 '1.25rem',我需要找到 <Typography variant='h4'> 的每个实例并手动更改它。

有没有办法给 createMuiTheme 添加断点,让它适用于所有实例?

我尝试了以下方法,但不起作用:

const defaultTheme = createMuiTheme()

const theme = createMuiTheme({
    typography: {
        h4: {
            [defaultTheme.breakpoints.down('xs')]: {
                fontSize: '1.5rem'
            }
        }
    }
})

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    更正:最初我表示您的解决方案不起作用,因为您使用的是不可能的条件,但我错了。从 xs 开始的“向下”包含 xs,因此它会执行您想要的操作(匹配 0px 到 600px)。

    我不确定我在最初的测试中做了什么导致我误入歧途,但可能导致混淆的一件事是您是否有多个 down 阈值。在我自己的测试中,通过使用breakpoints.only,我可以更轻松地避免射中自己的脚(例如,通过使用breakpoints.down("xs"),然后是后来的breakpoints.down("sm"),它胜过“xs”设置)。

    来自https://material-ui.com/layout/breakpoints/#breakpoints

    • xs,超小:0px 或更大
    • sm,小:600px 或更大

    这是一个更新的沙盒,它更清楚地显示了正在发生的事情:

    【讨论】:

    • 哦,太简单了!是的,它有效!感谢您的帮助!
    【解决方案2】:

    您可以通过 createBreakpoints 使用自定义断点。

    这是一个更改 MuiButton 的示例

    import createBreakpoints from '@material-ui/core/styles/createBreakpoints'
    
    const customBreakpointValues = {
      values: {
        xs: 0,
        sm: 576,
        md: 768,
        lg: 992,
        xl: 1200,
      },
    }
    
    const breakpoints = createBreakpoints({ ...customBreakpointValues })
    
    const theme = createMuiTheme({
      breakpoints: {
        ...customBreakpointValues,
      },
      components: {
        MuiButton: {
          styleOverrides: {
            root: {
              padding: '10px',
              [breakpoints.up('lg')]: {
                padding: '20px',
              },
            },
          },
        },
      },
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-13
      • 2023-03-15
      • 2015-01-26
      • 2014-06-18
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多