javascript - 使用 React.js 和 Material-UI 简化样式化的组件媒体查询
问题描述
我创建了三个函数来处理样式化组件中的媒体查询。一个用于处理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;
`}
或者一些类似的语法。我现在并不担心语法,因为我有一个函数而不是三个函数。
关于如何做到这一点的任何想法?
感谢(提前)您可以提供的任何帮助。
解决方案
我认为您正在尝试重新发明轮子,而不仅仅是遵循 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],
},
},
});
推荐阅读
- sql - 如何通过将 SQL 中的两列相乘来将舍入整数作为输出
- c# - 如何以正确的方式通过 http 发送二进制数据?
- mysql - 什么决定了mysql中多个完整性违规的顺序?如果多个列无效,哪个完整性违规将首先上升?
- javascript - Draw.io - 集成到另一个 HTML 页面
- java - UnsatisfiedDependencyException:创建名为“locationController”的 bean 时出错
- django - django rest框架从前端(8000)域而不是后端(8080)生成文件链接
- javascript - 我的 websocket 有两个连接,一个带有 ?sid 参数的连接一直失败,重试也不起作用,但有时它可以工作
- android - 有没有办法查看android的backstack?
- javascript - 清除输入切换以强制页面重新加载,而不是传统的输入清除
- mysql - 为缺少信息的客户添加银行身份验证