iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
3
Modern Web

React.js 從 【0】 到【1】推坑計畫 系列 第 12

【Day 12】Styled-component

原本今天要介紹其他主題的,但後來想想既然昨天都介紹 inline-style 了,今天就介紹另一種 styling 的方式 - styled-component 吧!

styled-component 是什麼?

styled-component 是一個 CSS-In-JS 的函式庫,使你可以在 JSX 中撰寫 CSS code,更方便的是他可以接到 component 的 props 值來動態改變 css 樣式。

首先透過 npm 安裝它

npm install styled-components

我的習慣是會把 styled-component 跟 component 的 code 拆開,最後再引入進去使用
https://ithelp.ithome.com.tw/upload/images/20190916/201132774Lf0K8R4tR.png

基本上使用方式非常簡單,styled.div 也可以替換成 styled.img 或 styled.h1 等任何 HTML TAG。

<div style={{display:'flex',justifyContent:'center',alignItems:'center',marginTop:'25px'}}>
    <DetailTitle>單次掃描資訊</DetailTitle>
</div>

將 styled-component 引入到 component code 後就可以把它當作是一般 component 來使用。

搭配 props 使用

const Title = styled.div`
  padding: 20px 0 0 20px;
  font-size: 48px;
  color: ${props => (props.skyblue ? 'skyblue' : 'black')};
`

<Title skyblue={true}>This is my title</Title>

透過這種方式我們就可以依賴 props 來達成動態改動 style。

Styled component 的缺點

https://ithelp.ithome.com.tw/upload/images/20190916/201132776AzO68U8KA.png

當你打開 browser devtool 想看看自己用 styled-component 建構的元件擁有哪些 class 時,只會看到一堆 styled-component 自動產生的亂碼,雖然能夠確保 class name 不會衝突,但當你想知道特定 class 代表的是哪些 style 時,只能夠回到 code 去看,造成未來 debug 與 testing 的困難。

別擔心!解法來啦!

import React from 'react'
import styled from 'styled-components'

const Element = ({ red, className }) => {
  return (
    <div className={className}>
      <div className="element__img" />
      <div className="element__info">
        <div className="element__title" skyblue>
          Cute Puppy
        </div>
        <div className="element__description">
          Sed ut voluptatem neque cumque. Qui sed ut itaque est doloribus qui.
          Eos perferendis autem qui fugiat.
        </div>
      </div>
    </div>
  )
}

const StyledElement = styled(Element)`
  width: 80%;
  height: 300px;
  box-shadow: 0 0 5px 2px #ccc;
  .element__img {
    display: inline-block;
    width: 300px;
    height: 100%;
    background-image: url('this is background url');
  }
  .element__info {
    display: inline-block;
    vertical-align: top;
    width: calc(100% - 300px);
    height: 100%;
    text-align: left;
    .element__title {
      padding: 20px 0 0 20px;
      font-size: 48px;
      color: ${props => (props.red ? 'red' : 'black')};
    }
    .element__description {
      padding: 20px;
      font-size: 30px;
      font-style: italic;
      color: #888888;
    }
  }
`

export default StyledElement

定義在 class 以外的 全域 style 會變成 className 的 props 傳進去,而調整後我們也可以掌控 class 的名字了,寫起來像是在寫 CSS 卻不需要額外寫在 CSS 檔案裡頭,不管是開發上還是 debug 甚至測試上再至效能上都有所提升囉!


上一篇
【Day 10】CSS && Inline-style
下一篇
【Day 13】Conditional Rendering
系列文
React.js 從 【0】 到【1】推坑計畫 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
阿尼
iT邦新手 5 級 ‧ 2019-09-18 22:25:18

npm install styled-components 少了s
想說怎麼會找不到

感謝更正~

我要留言

立即登入留言