從今天開始認識 CSS-In-JS。
inline style
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | function Title () {
 
 const tiltestyle = {
 color : 'yellow',
 fontSize: '3em',
 backgroundColor: 'green',
 padding: '10px'
 }
 return <h1 style={tiltestyle}>Hello Big man</h1>
 }
 function App() {
 return (
 <div className="App">
 <Title />
 </div>
 );
 }
 
 | 
熟悉的 className
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | import './App.css';
 function App() {
 return (
 <div className="App">
 <Title />
 </div>
 );
 }
 
 | 
因為 class 是保留字,所以改用 className 來表示。
CSS-In-JS(styled Component)
目前的兩大主流應該是 Emotion 或 styled-components,我目前學的是後者。
兩種雖然有些差別,但主要的 pattern 差別不大,總之寫起來大概會像這樣:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | const Button = styled.button`display: inline-block;
 border-radius: 4px;
 padding: 8px 12px;
 background-color: black;
 border: none;
 color: white;
 cursor: pointer;
 
 &:hover {
 color: red;
 }
 `
 
 | 
就如同「styled-componet」這個名稱,它就跟建立一個 Component 沒兩樣,只是可以在裡面寫 CSS。
這樣寫的特點有幾個:
- 可以寫 SCSS 語法(畢竟本質上還是 JS,得先經過轉譯)
- 不用管 class 會不會衝突,它會幫你自動產生一個很像亂數的 class Name
- 不用管 prefix,它會自動加(好棒棒!)