iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
Modern Web

寫出好維護又簡潔的 react 程式碼 feat: Function Programming系列 第 7

day7: CSS style 規劃 - CSS in JS(emotion 使用 - 1)

在上一篇我們介紹的 CSS in JS, 那這次我們來使用 CSS in JS 的框架 emotion, 目前 css in js 主流的框架大概有 css module, styled-component 和 emotion 這三套,這邊因為作者本人平常習慣使用 emotion css, 所以直接用這套來使用。

安裝

這裡的範例皆使用 create react app 來示範

  1. 使用 emotion 的 CSS, classname 作法
npm install --save @emotion/css
import { css, cx } from '@emotion/css'

const color = 'red'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
			color:${color};
    `}
  >
    Demo
  </div>
)

使用這個做法,emotion 會使用 css 將 css 轉成一個具有 hash 的隨機 className ex: css-2342342 ,也可以將 `css``` 的內容變成一個變數,方便管理 css

import { css, cx } from '@emotion/css'

const color = 'red'

const rootStyle = css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
			color:${color};
    `

render(
  <div
    className={rootStyle}
  >
    Demo
  </div>
)

另外在 emotion className 底下的 css, 也可以像是一般 scss 一樣, 可以嵌套指向子層,或是用 & 同一個 element 的不同狀態的 className。注意這邊要經由狀態增加或減少 clssName 時,可以用 emotion 提供的 cx, 去幫助 className 的增加或減少。

import {useState} from 'react'
import { css, cx } from '@emotion/css'

const [isActive,setIsActive] = useState(true)

const color = 'red'

const rootStyle = css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
			color:${color};
			&.active{
				color:blue;
			}
			.text{
				color:black;
				font-size:12px;
			}
    `

render(
  <div
    className={cx(rootStyle,isActive && '.active')}
  >
		thie is demo.
    <p className="text" >hello</p>
  </div>
)

如果要使用 globalCSS 的話也可以使用 injectGlobal ,這個 emotion 內建語法, 這樣全部的 element 都可以吃到這些 style

import {useState} from 'react'
import { injectGlobal } from '@emotion/css'

injectGlobal`
	* {
		box-sizing:border-box;
  }
  font-family: 'Robot';
`

https://emotion.sh/docs/install


上一篇
day6: CSS style 規劃 - CSS in js
下一篇
day8: CSS style 規劃 - CSS in JS(emotion 使用 - 2)
系列文
寫出好維護又簡潔的 react 程式碼 feat: Function Programming30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言