gpt4 book ai didi

javascript - 使用 React.js 和 Material-UI 简化样式组件媒体查询

转载 作者:行者123 更新时间:2023-11-28 03:25:44 24 4
gpt4 key购买 nike

我创建了三个函数来处理样式组件中的媒体查询。第一个用于处理 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;
`}

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

关于如何做到这一点有什么想法吗?

(预先)感谢您提供的任何帮助。

最佳答案

我认为您正在尝试重新发明轮子,而不是仅仅遵循 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],
},
},
});

关于javascript - 使用 React.js 和 Material-UI 简化样式组件媒体查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58648955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com