從 npm 安裝 styled-components :
npm install --save styled-components
強烈推薦使用 styled-components 的 babel 插件 (當然這不是必須的).它提供了許多益處,比如更清晰的類名,SSR 兼容性,更小的包等等.
如果沒有使用模塊管理工具或者包管理工具,也可以使用官方托管在 unpkg CDN 上的構建版本.只需在HTML文件底部添加以下<script>標簽:
<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 通過標記的模板字符來設置組件樣式.
它移除了組件和樣式之間的映射.當我們通過styled-components定義樣式時,我們實際上是創(chuàng)建了一個附加了樣式的常規(guī) React 組件.
以下的例子創(chuàng)建了兩個簡單的附加了樣式的組件, 一個Wrapper和一個Title:
// 創(chuàng)建一個 Title 組件,它將渲染一個附加了樣式的 <h1> 標簽 const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; `; // 創(chuàng)建一個 Wrapper 組件,它將渲染一個附加了樣式的 <section> 標簽 const Wrapper = styled.section` padding: 4em; background: papayawhip; `; // 就像使用常規(guī) React 組件一樣使用 Title 和 Wrapper render( <Wrapper> <Title> Hello World! </Title> </Wrapper> );
注意styled-components 會為我們自動創(chuàng)建 CSS 前綴
更多建議: