styled-components 就決定是你了
寫 CSS 搭配上其他模組已經都不是新鮮事情,CSS 要經過編譯可以變成可繼承,可覆寫,可重複使用 mixin 的方式已經都是日常所見。
隨著框架的發展,大家有各自不同的搭配方式,在使用一小段 react 時間之後,我們採用過 radium,還有許多 inline-style 的方式,不過 inline 實在不是我的菜。
因此開始採用了 styled-components ,上述只是其中一個原因,實際上採用 styled-components 與 react 搭配上,變的更為清爽簡潔。
styled-components
Use the best bits of ES6 and CSS to style your apps without stress
- 官方網站:https://www.styled-components.com/
- 官方資料:https://www.styled-components.com/docs/basics#getting-started
就是要用最潮的寫法,潮,除了用巢狀表示式之外, 還可以搭配許多方法 - ES6,其中更主要的一個方式,是受到 component 的概念為核心,任何一個 CSS style 都是一個新的模組,全新的 component,可以在經過重重包裝之後,又延伸出新的 component。
所以編寫方式會跟以前的寫法,有點類似又不太像
styled-components 使用方法
主要使用語法,採用 ES6 template 表示方式,
import styled from 'styled-components';
const Button = styled.button`
border-radius: 3px;
padding: 0.25em 1em;
margin: 0 1em;
background: transparent;
color: palevioletred;
border: 2px solid palevioletred;
`
接下來你就可以用 react 的方式直接進行 render 產出。
render(
<div>
<Button>Normal Button</Button>
</div>
)
實際上你會看到產出,還是以 div 包裝之外,實際上 styled 會進行自動編譯,自動產出 class name 搭配專屬的屬性使用,這對於在 production 環境上可以做到更好的混淆及壓縮,讓 class name 可以自動壓縮到更小。
另外一方面,在 react-tools 底下,我們還是可以直接從 components 看出程式的結構,在除錯的時候會十分方便。
事實上,當你寫好一個 styled components 可以直接視為一個小的 react components ,還可以直接承接 props 等屬性進入,可以直接與 react component 進行無縫結合。
styled-components 導入前該想的事情
在開始使用之前,我們先想想情境,如果你是單純採用 jQuery 的好朋友,基本上導入 styled-components 這樣的項目對你來說並沒有任何好處。
styled-components 對自己經驗來說,搭配 react 才會出現顯著的效果(廢話),特別已經習慣寫 ES6 語法的朋友或覺得十分爽快。
當然一開始要適應一下,覺得為何寫一個簡單的 CSS ,現在都要搞得這麼複雜,不過實際上在切開 store / container / component ,你會發現所有的事情都可以讓 styled 跟著 component 一起進行,互相不會有太多過度依賴,命名上也不會有任何混淆。
就讓你的 button style 就直接是一個 button, 讓你的 form input sylte 直接是一個全新的 input,要多直覺,有多直覺,給你一個痛快。
結語
講了這麼多,主要是分享 styled-components 自己用了一段時間後的感覺,以目前 react CSS 解決方案來說,styled-components 是真的很漂亮的一個解法,也是很值得使用的套件。
如果你是 react 使用者,已經讓許多 inline fxxking style 追蹤到起校,還有一些在 component 多重混用下,會有 style 爆炸的狀態,或者是你還在觀望想說回到 SASS 的懷抱,給你一個建議 - Come with me! - styled-components
NOW !
特別感謝 Zet 大大 介紹,讓我們知道 styled-components 這樣的套件,也將這部分進行了講解,讓小弟可以在短時間內窺見 react + styled 的奧秘。