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

时间:2019-04-25 18:43:13

标签: reactjs material-ui

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

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

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

const styles = (theme) => ({
    myElement: {
        ...theme.headings.h1,
        // ... other styles
    }
}

这确实有效,但是我面临的问题是我希望标题能够响应并尊重Material UI的断点,但是我不能在createMuiTheme本身内使用它们吗?正确地执行此操作的方法是什么,以便我可以将自己的样式散布成一个包含所有响应式样式的样式?

4 个答案:

答案 0 :(得分:2)

这是一个旁注,但是如果您想更改断点的值,则可以编辑使用breakpoints创建的createBreakpoints({})对象:

import createBreakpoints from '@material-ui/core/styles/createBreakpoints'

const breakpoints = createBreakpoints({})
// outputs {xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920}

breakpoints.values.lg = 1024
// outputs {xs: 0, sm: 600, md: 960, lg: 1024, xl: 1920}

如果您不想编辑现有项目,也可以类似的方式添加其他断点:

breakpoints.values['xxl'] = 3000
// outputs {xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920, xxl: 3000}

在我的项目中,Material-UI设置的断点(xs:0,sm:600等)与我在项目中已经使用的断点不符,因此我必须更改它们。 / p>

答案 1 :(得分:1)

您可以使用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

(已测试:material-ui 4.0.1)

答案 2 :(得分:1)

来自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,
    },
  },
};

答案 3 :(得分:-1)

const theme = createMuiTheme();

theme.typography.h3 = {
  fontSize: '1.2rem',
  '@media (min-width:600px)': {
    fontSize: '1.5rem',
  },
  [theme.breakpoints.up('md')]: {
    fontSize: '2.4rem',
  },
};

https://material-ui.com/customization/typography/#responsive-font-sizes