React 中帶有樣式組件的簡單媒體查詢
有時被忽視的css
styled-components 中的標籤可以幫助您以自己的樣式編寫媒體查詢。
例如,假設您有以下斷點(以 px 為單位):
let theme = {
breakpoints: {
mobile: { value: 450 },
tablet: { value: 700 },
desktop: { value: 900 }
}
}
您可能正在為您的應用設置重置,如下所示:
const GlobalStyle = createGlobalStyle`
*, *:before, *:after{
padding: 0;
margin: 0;
box-sizing: inherit;
}
html{
box-sizing: border-box;
/* set default font size i.e. 1rem to 62.5% of 16px=10px */
font-size: 62.5%;
}
`
但也許你希望默認字體大小根據你的斷點來改變!
您可以在整個應用程序中編寫普通的媒體查詢,但這有點笨拙吧?
@media only screen and (max-width: ${theme.breakpoints[bp].value / 16}em) {
${css(...args)}
}
這就是 css
可以進來...
import { css } from "styled-components";
theme.media = {};
Object.keys(theme.breakpoints).map(bp => {
theme.media[bp] = (...args) => css`
@media only screen and (max-width: ${theme.breakpoints[bp].value / 16}em) {
${css(...args)}
}
`;
});
theme.media.min = {};
Object.keys(theme.breakpoints).map(bp => {
theme.media.min[bp] = (...args) => css`
@media only screen and (min-width: ${theme.breakpoints[bp].value / 16}em) {
${css(...args)}
}
`;
});
這是怎麼回事?
正如文檔所建議的那樣, css
功能與樣式化組件通常的 styled.tag_method
並沒有太大的不同 因為它會為你插值(通常的 ${props=>props.blah}
)。我們在這裡所做的是創建我們自己的標籤(theme.media.breakpoint_name
s + theme.media.min.breakpoint_name
s 分別代表最大和最小查詢),我們可以使用它來生成 將插入到通常的 styled.tag_method
中的 css !
現在讓字體大小響應:
const GlobalStyle = createGlobalStyle`
*, *:before, *:after{
padding: 0;
margin: 0;
box-sizing: inherit;
}
html{
box-sizing: border-box;
font-size: 62.5%;
${theme.media.tablet`
font-size: 50%;`}
${theme.media.mobile`
font-size: 40%;`}
}
`
簡單😎
注意:如果主題不在範圍內,您將需要使用回調,例如props=>props.theme.media.tablet
通過哪些樣式化的組件將通過上下文給定的主題與道具水合
感謝您的閱讀。認為這是一個有用的模式🤓?讓我知道!覺得是垃圾?讓我知道什麼更好💡有問題嗎?只要問⬇️
你也可以在我的個人網站上看到這篇文章。