首页 > 解决方案 > 使用 React.js 和 Material-UI 简化样式化的组件媒体查询

问题描述

我创建了三个函数来处理样式化组件中的媒体查询。一个用于处理min-width媒体查询,第二个用于处理max-width和查询,第三个用于处理min-widthmax-width查询。

他们来了:

const breakpoints = {
  tablet: 768,
  desktop: 1024,
  widescreen: 1216,
  fullhd: 1408
}

const breakpointsKeys = Object.keys(breakpoints)

const media = Object.keys(breakpoints).reduce((obj, query) => {
  let queryUnit

  if (typeof mediaQueryUnit !== 'undefined') {
    queryUnit = mediaQueryUnit
  } else {
    queryUnit = 'px'
  }
  obj[query] = (...styles) => css`
    @media (min-width: ${breakpoints[query] + queryUnit}) {
      ${css(...styles)}
    }
  `
  return obj
}, {})



const mediaDown = Object.keys(breakpoints).reduce((obj, query) => {
  let queryUnit

  if (typeof mediaQueryUnit !== 'undefined') {
    queryUnit = mediaQueryUnit
  } else {
    queryUnit = 'px'
  }
  obj[query] = (...styles) => css`
    @media (max-width: ${breakpoints[query] - 1 + queryUnit}) {
      ${css(...styles)}
    }
  `
  return obj
}, {})

const mediaOnly = Object.keys(breakpoints).reduce((obj, query, index) => {
  let nextIndex = breakpointsKeys.indexOf(query) + 1
  let nextIndexQuery = breakpointsKeys[nextIndex]
  let maxQuery = breakpoints[nextIndexQuery]

  let queryUnit

  if (typeof mediaQueryUnit !== 'undefined') {
    queryUnit = mediaQueryUnit
  } else {
    queryUnit = 'px'
  }
  obj[query] = (...styles) =>
    maxQuery &&
    css`
      @media (min-width: ${breakpoints[query] +
          queryUnit}) and (max-width: ${maxQuery + queryUnit}) {
        ${css(...styles)}
      }
    `
  return obj
}, {})

这就是我在样式组件中使用它们的方式:

const Button = styled.div(
  ({
    tablet,
    tabletDown,
    tabletOnly,
  }) => css`

    ${media.tablet`
      background: blue;
   `}

   ${media.tabletDown`
     background: yellow;
   `}

   ${media.tabletOnly`
     background: green;
   `}
  `
)

我想做的是将这三个功能组合成一个功能。然后我可以像这样使用它:

${media.down.tablet`
  background-color: yellow;
`}

或者一些类似的语法。我现在并不担心语法,因为我有一个函数而不是三个函数。

关于如何做到这一点的任何想法?

感谢(提前)您可以提供的任何帮助。

标签: javascriptreactjsmaterial-designmaterial-uistyled-components

解决方案


我认为您正在尝试重新发明轮子,而不仅仅是遵循 Material-UI 的现有功能:https ://material-ui.com/customization/breakpoints/

const styles = theme => ({
  root: {
    padding: theme.spacing(1),
    [theme.breakpoints.down('sm')]: {
      backgroundColor: theme.palette.secondary.main,
    },
    [theme.breakpoints.up('md')]: {
      backgroundColor: theme.palette.primary.main,
    },
    [theme.breakpoints.up('lg')]: {
      backgroundColor: green[500],
    },
  },
});

推荐阅读