W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
從 npm 安裝 styled-components :
npm install --save styled-components
強烈推薦使用 styled-components 的 babel 插件 (當(dāng)然這不是必須的).它提供了許多益處,比如更清晰的類名,SSR 兼容性,更小的包等等.
如果沒有使用模塊管理工具或者包管理工具,也可以使用官方托管在 unpkg CDN 上的構(gòu)建版本.只需在HTML文件底部添加以下<script>標(biāo)簽:
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js" rel="external nofollow" ></script>
添加 styled-components 之后就可以訪問全局的 window.styled 變量.
const Component = window.styled.div` color: red; `
注意這用使用方式需要頁面在 styled-components script 之前引入 react CDN bundles
styled-components 通過標(biāo)記的模板字符來設(shè)置組件樣式.
它移除了組件和樣式之間的映射.當(dāng)我們通過styled-components定義樣式時,我們實際上是創(chuàng)建了一個附加了樣式的常規(guī) React 組件.
以下的例子創(chuàng)建了兩個簡單的附加了樣式的組件, 一個Wrapper和一個Title:
// 創(chuàng)建一個 Title 組件,它將渲染一個附加了樣式的 <h1> 標(biāo)簽 const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; `; // 創(chuàng)建一個 Wrapper 組件,它將渲染一個附加了樣式的 <section> 標(biāo)簽 const Wrapper = styled.section` padding: 4em; background: papayawhip; `; // 就像使用常規(guī) React 組件一樣使用 Title 和 Wrapper render( <Wrapper> <Title> Hello World! </Title> </Wrapper> );
注意styled-components 會為我們自動創(chuàng)建 CSS 前綴
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: