iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
0
自我挑戰組

React初心者30天的探索之路系列 第 10

[Day 10] React CSS 最重要的小事(上)

今天要來介紹在React裡面有哪幾種撰寫css的方式

方法1:inline-style:

這是我最不習慣的寫法,畢竟要用駝峰式的格式寫,就沒有樣式語法自動提示了,是有多懶,而且這樣寫不支援偽類選擇器:before :after等等

    render() {
        const style = {
            fontWeight:'bold',
            fontSize: 18,
         }
        return (
            <Fragment>
                {
                    this.state.order.map((item)=>{
                        return (<li style={style}>{item}</li>)
                    })
                }
            </Fragment>
        )
    }

方法2:樣式檔案獨立

將樣式獨立成一隻檔案(css、sass、scss),如果有用sass記得要先安裝node-sass,不過這樣的缺點是無法做到scoped

  yarn add node-sass

再引入即可

import './scss/test.scss'

方法3:css module

1.css檔名以 xxx.module.css命名,如果是scss就是xxx.module.scss
2.用import變數的方式引入樣式檔案
3.className傳入變數底下定義的class

import style from './style/Title.module.scss'
class CssModuleExample extends Component {
    render() {
        return (
            <div>
                <h1 className ={style.main_title}>hello</h1>
            </div>
        )
    }
}

這是樣式檔案

Title.module.scss

.main_title{
    color:olive;
}

打開F12看就會發現class後面帶有hash

有寫過vue的人應該知道,在.vue檔案裡的style標籤加上scoped屬性就會具備css module的功能,那麼這樣的好處是什麼?a和b檔案可以各自擁有同名的class而不會互相影響,這真的很重要!原理就是在編譯後會在class名稱上加上hash值,確保class唯一而不重複

那如果有一個情境是我想要這個class是全域的呢?可以利用:global來達成

:global(.main_title){
  color:olive;
}

引入的方式也要調整一下,不用傳物件,直接給字串即可

<h1 className ="main_title">hello</h1>

另外有一個我覺得還挺有趣的功能,叫做composes,功能有點像是sass的mixin

這樣寫main_title就會吃到title設定的樣式了

Title.module.scss

.title{
 font-style:italic;
}


.main_title{
 composes:title;
 color:steelblue;
}

另外 也可以將.scss檔作為composes

other.scss


.light{
    opacity: 0.5;
}

Title.module.scss

.main_title{
 composes:light from './other.scss';
}

明天會繼續介紹,被稱作是React 樣式最佳方案 -- style components


上一篇
[Day 09] React State & props
下一篇
[Day 11] React CSS 最重要的小事(下)
系列文
React初心者30天的探索之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言