我创建了三个函数来处理样式化组件中的媒体查询。一种用于处理min-width
媒体查询,第二种用于处理max-width
,第三种用于min-width
和max-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;
`}
或一些类似的语法。我现在不担心语法,而只是拥有一个函数而不是三个函数。
关于如何执行此操作的任何想法?
(提前)感谢您可以提供的帮助。
答案 0 :(得分:0)
我认为您正在尝试重新发明轮子,而不是仅仅遵循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],
},
},
});