如何在 createMuiTheme 中使用断点?材质 UI 和 React.js

Tay*_*ach 11 reactjs material-ui

也许不是正确的方法,但我想为标题创建一些“全局”样式。像这样的东西:

const myTheme = createMuiTheme({
    headings: {
        h1: {
            fontSize: 28,
            // Obviously this does not work...
            [theme.breakpoints.down('sm')]: {
                fontSize: 24
            },
        },
        h2: {
            fontSize: 24,
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我可以像这样在我的组件中使用它们:

const styles = (theme) => ({
    myElement: {
        ...theme.headings.h1,
        // ... other styles
    }
}
Run Code Online (Sandbox Code Playgroud)

这确实有效,但我面临的问题是我希望标题具有响应性并尊重 Material UI 的断点,但我不能在 createMuiTheme 本身中使用它们?有什么方法可以正确执行此操作,以便我可以将所有样式都包含在响应式样式中?

Ric*_*las 22

您可以使用该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('md')]: {
          minWidth: '200px',
          backgroundColor: 'yellow',
        },
      },
    },
  },
})

export default theme
Run Code Online (Sandbox Code Playgroud)

(测试:material-ui 4.0.1)

  • 是的,我决定创建另一个虚拟的空白主题,然后在我的主主题中使用该主题。同类型的东西。 (2认同)
  • createBreakpoints 被认为是私有的 https://material-ui.com/guides/minimizing-bundle-size/#option-1 “请注意,我们只支持第一级和第二级导入。任何更深层次的内容都被认为是私有的,并且可能会导致问题,例如作为包中的模块重复。” (2认同)

Eri*_*rel 16

V5更新

首选的解决方案是创建一个中间主题(源):

let theme = createTheme()
theme = createTheme(theme , { 
  h5: {
          fontSize: "1.5", //24px
          fontWeight: title.fontWeight,
          fontFamily: sansSerif(title.fontFamily),
          letterSpacing: title.letterSpacing,
          lineHeight: "2.1rem", //34px
          color: "#636e72",
          [theme.breakpoints.between("xs", "sm")]: {
            fontSize: "1.25rem", // 20px
            lineHeight: "1.9rem", //  30px
          },
          [theme.breakpoints.between("sm", "md")]: {
            fontSize: "1.4rem", //24px
            lineHeight: "2rem", // 35px
          },
        },
})
Run Code Online (Sandbox Code Playgroud)

如果您使用createBreakpoints: 正如@Ricardo Canelas 评论所指出的那样,createBreakpoints它只是移动了,现在正确的导入是:import createBreakpoints from "@mui/system/createTheme/createBreakpoints"。但是,请记住,在撰写本文时这仍然是私有 API,因此可以在任何版本更新时移动/中断。首选解决方案是使用中间主题。


Tho*_*mas 6

来自https://github.com/mui-org/material-ui/issues/18017#issuecomment-545914925

import { createMuiTheme } from "@material-ui/core/styles";

const theme = createMuiTheme();

theme.overrides = {
  MuiTypography: {
    hero: {
      [theme.breakpoints.up('md')]:{
        fontSize: '11rem',
        background: 'red',
      },
      fontSize: '3.75rem',
      lineHeight: '5rem',
      fontWeight: 700,
    },
  },
};
Run Code Online (Sandbox Code Playgroud)