iT邦幫忙

2021 iThome 鐵人賽

DAY 6
0
Modern Web

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

day6: CSS style 規劃 - CSS in js

在經歷了傳統 CSS 後,發現了一些 CSS 的缺點

  • 全域污染 - CSS class name 會全域會覆蓋,譬如有個叫 card 的 classname .card {},假設是寫在純 css 檔中,使用 import 'app.css' 的方式引用,在其他 component 的 html 同樣具有 card 的class name,將會吃到這個相同的屬性,並不能針對不同 component 有獨特的 style 樣式,會污染其他 component。
  • 不能動態產生 CSS - 譬如有個 div 的 height 是根據判斷產生的,在傳統的使用上需要用 var() 的方式判斷,但是這樣會造成在 html 的 style 埋下過多的 var 元素,並在舊 IE 上並不支援度。

Untitled

使用 css 方式
//example.js

useEffect(()=>{
	document.querySelect('.customer-container').style.setProperty('--current-height',
  '200px')
},[])
<div classname="customer-container"></div>

//example.css
{
 .customer-container{
   height:var(--current-height);
  }
}

//這邊一個 height 就要埋一個變數,試想假設有 width 或其他變數,也會造成埋過多的 var 屬性

使用 style-component 寫法

<Wrapper width={width} height={height} />
</Wrapper>

const Wrapper = styled.div`
  width: ${p => p.width};
  height: ${p => p.height};
`;

// 這樣的寫法就乾淨很多,而且可以帶很多變數當成 props 到 Wrapper
  • css 需要用 bem 或是 oocss 的命名方式來拆分組件,但是其實只是為了拆分組件而命名,如果使用

CSS in JS 則不用考慮過多的命名

// 使用傳統 css
// BEM 命名, 為了區別 nav 區塊需要命名 nav__item, 命名狀態需要 --active
  <div class="nav">
    <li class="nav__item nav__item--active"><a href="#about">About</a></li>
    <li class="nav__item"><a href="#product">Product</a></li>
  </div>

//使用 emotion
<div
    css={css`
     ......
    `}
  >
    <li
      css={css`
       ....
      `}
    >
     <a href="#about">About</a>
    </li>
		<li
      css={css`
       ....
      `}
    >
     <a href="#product">Product</a>
    </li>
  </div>
//在每個 element 都有屬於自己的 css 樣式,就不用過度命名

這時候我們就需要依靠 CSS in JS 來解決這些缺點,我們下一篇將介紹 emotion css 的使用。

https://blog.logrocket.com/5-things-you-can-do-css-in-js/

https://www.joshwcomeau.com/css/styled-components/

https://dev.to/rleija_/5-reasons-to-go-with-css-in-js-for-your-next-application-43m

https://blog.logrocket.com/5-things-you-can-do-css-in-js/


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

尚未有邦友留言

立即登入留言