開發(fā)響應(yīng)式 web app 時(shí)媒體查詢是不可或缺的工具.
以下是一個(gè)非常簡(jiǎn)單的示例,展示了當(dāng)屏寬小于700px時(shí),組件如何改變背景色:
const Content = styled.div` background: papayawhip; height: 3em; width: 3em; @media (max-width: 700px) { background: palevioletred; } `; render( <Content /> );
由于媒體查詢很長(zhǎng),并且常常在應(yīng)用中重復(fù)出現(xiàn),因此有必要為其創(chuàng)建模板.
由于 JavaScript 的函數(shù)式特性,我們可以輕松的定義自己的標(biāo)記模板字符串用于包裝媒體查詢中的樣式.我們重寫一下上個(gè)例子來(lái)試試:
const sizes = { desktop: 992, tablet: 768, phone: 576, } // Iterate through the sizes and create a media template const media = Object.keys(sizes).reduce((acc, label) => { acc[label] = (...args) => css` @media (max-width: ${sizes[label] / 16}em) { ${css(...args)} } ` return acc }, {}) const Content = styled.div` height: 3em; width: 3em; background: papayawhip; /* Now we have our methods on media and can use them instead of raw queries */ ${media.desktop`background: dodgerblue;`} ${media.tablet`background: mediumseagreen;`} ${media.phone`background: palevioletred;`} `; render( <Content /> );
更多建議: