我编写了以下代码以简化React应用程序中样式化组件主题化中的媒体查询。
theme.js
export const theme = {
// Color Parette
color: {
...
},
// Media Query
media: {
device: {
min: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200
},
query: (lower, upper) => {
var queryString;
if (lower != null && upper != null) {
queryString = `@media screen and (min-width: ${lower}px) and (max-width: ${upper}px)`;
} else if (lower != null) {
queryString = `@media screen and (min-width: ${lower}px)`;
} else if (upper != null) {
queryString = `@media screen and (max-width: ${upper}px)`;
} else {
queryString = `@media screen and (min-width: 0px)`;
}
return queryString;
}
}
};
NavMenu.js
//imports
//theme.js is imported to index.js and applied to ThemeProvider component
export default function NavMenu(props) {
return (
<div>
<StyledNavbar>
... //contents
</StyledNavbar>
</div>
);
}
//Styled Components
const StyledNavbar = styled(Navbar)`
${props => props.theme.media.query(props.theme.media.device.md)} {
color: ${props => props.theme.color.primary.default};
}
`;
,但不确定这是否是一种好方法。我担心的是:
props.theme.media.query(props.theme.media.device.xx)
。const query = props.theme.media.query
中定义类似NavMenu.js
的东西吗?如果不需要上面的信息,请告诉我。