【问题标题】:In material-ui, how can I set different theme-styles for different breakpoints?在material-ui中,如何为不同的断点设置不同的主题样式?
【发布时间】:2018-08-10 12:15:59
【问题描述】:

本题针对 material-ui 1.0。

当我使用createMuiTheme 创建主题时,如何为不同的断点设置不同的样式,例如typography.title?在组件级别上,我可以通过以下方式实现:

const styles = theme => ({
  title: {
    fontSize: 34,
  },
  [theme.breakpoints.down('sm')]: {
    title: {
      fontSize: 28,
    }
  },
})

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    Material-ui 确实有很多不同的主题解决方案。当您寻找对您有用的东西时,您正在寻找两件事:

    1. 创建可应用于组件层次结构的主题。

    文档页面“Nesting the theme

    1. 更改单个样式规则,同时保持其他样式规则不变。

    文档页面“Customizing all instances of component type” 和“Typography API

    让它工作的关键是创建第二个可以看到断点的主题,并为它提供一些特殊的选项来覆盖排版:

    ...outerTheme,
    overrides: {
      MuiTypography: {
        title: {
          [outerTheme.breakpoints.down("sm")]: {
            fontSize: 28
          },
        }
      }
    }
    

    我发现“嵌套主题”示例代码适合对其进行测试,因此它可能如下所示: codeandbox.io/s/98192p85zy

    编辑:替换了最终的代码链接,使其成为比文档中的示例更有用的答案。

    【讨论】:

    • 我把你的代码压缩到了绝对最小值 (codesandbox.io/s/nw0pllwr04)。这似乎可行,但这意味着我总是必须使用两个嵌套的 并在第二个中进行所有真正的主题化?
    • 嗯,这个想法是只在根级别提供一个基本主题。嵌套的“realTheme”定义不需要与“baseTheme”在同一范围内,只要有一个(参见possible refactor)。我还尝试了a workaround,它有效,但警告消息显示它不是它的预期用途。
    • 好的,现在我想出了另一种只使用一个 的方法。也许这更像您正在寻找的:codesandbox.io/s/98192p85zy?如果是这样,我可以编辑答案中的链接以使其更有用。
    • 这确实看起来很像我需要的。谢谢!
    【解决方案2】:

    还有另一种方法可以通过断点方法使用 createMuiTheme

    如果您检查 createMuiTheme 核心,您会看到它使用了 createBreakpoints 类。

    所以,你可以这样做:

    // theme.js
    
    import createBreakpoints from '@material-ui/core/styles/createBreakpoints'
    import { createMuiTheme } from '@material-ui/core/styles'
    
    const breakpoints = createBreakpoints({})
    
    const theme = createMuiTheme({
      overrides: {
        MuiTab: {
          root: {
            [breakpoints.up('lg')]: {
              minWidth: '200px',
              backgroundColor: 'yellow',
            },
          },
          wrapper: {
            padding: '0 10px',
            backgroundColor: 'black',
          },
        },
      },
    })
    
    export default theme
    

    (已测试:@material-ui/core 4.0.1)

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 2022-08-10
      • 1970-01-01
      • 2013-09-01
      相关资源
      最近更新 更多