99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

styled-components 媒體模板

2020-07-24 17:16 更新

媒體模板

開發(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 />
);


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)