Peiyun Lee
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ###### tags: `前端技能樹` # 在JS中寫CSS,神套件Styled-components 要如何在 React 中撰寫 CSS,為元素添加樣式?目前的方法有 Inline-Style、CSS Modules...,其中一個方法就是很多人使用的 Styled-components。**Styled-components 是一個 CSS-in-JS 函式庫,讓我們可以在 JS 中撰寫 CSS**,直接針對 React Component 去進行樣式設定,並且同時解決了 CSS 常遇到的命名衝突的問題。 ## Styling a component Styled-components 利用了 Javascript 的樣板字面值(Template literals)來設置組建的樣式,允許在字串中嵌入運算式,字串用反引號 ` `` ` 取代單雙引號包住;運算式則由 `$` 字元和 `{}` 包裹組成,舉例如下: ```javascript= `string ${expression} string` ``` **設定樣式的同時,Styled-components 會直接建立一個 React Component,包含所指定的 Element**。比如下面我們針對 ```<h2>``` 元素設定樣式,同時建立成一個 Component ```<Title>```: ```javascript= import styled from "styled-components"; const Title = styled.h2` font-size: 20px; color: red; `; ``` ```jsx= render( <div> <Title>標題文字</Title> </div> ); ``` ![](https://i.imgur.com/J6FwjDN.png) ## 根據Props改變樣式 當我們建立的是一個普通的 React Component,就代表可以在組件間傳遞 Props,配上樣板字面值的功能,針對組件的樣式進行調整就變得很方便。舉例如下,若 ```<Title>``` 有設置 Prop ```red``` 就顯示紅色的文字,沒有就顯示黑色的文字: ```javascript= const Title = styled.h2` font-size: 20px; color: ${props => props.red ? "red" : "black"}; `; ``` ```jsx= render( <div> <Title red>標題文字</Title> <Title>標題文字</Title> </div> ); ``` ![](https://i.imgur.com/WdIXxX6.png) ## 擴展樣式 在 React 中,會常常使用同一個 Component 來建立相同的 UI,而我們可能希望針對各別組件去稍微修改它的樣式, Styled-components就提供了一個方法,**只需要將基礎組件包在 ```styled()``` 內,就能夠繼承組件樣式再擴展出一個新的組件**。比如前一個範例,可以用下面的程式碼做到相同的效果: ```javascript= const Title = styled.h2` font-size: 20px; color: black; `; const RedTitle = styled(Title)` color: red; `; ``` ```jsx= render( <div> <RedTitle>標題文字</RedTitle> <Title>標題文字</Title> </div> ); ``` 或者我們想要改變的是 Component 的標籤或繼承組件,可以利用 Prop ```as```指定,比如將第二個標題從 ```<h2>``` 改成 ```<p>``` 元素: ```jsx= render( <div> <RedTitle>標題文字</RedTitle> <Title as="p">標題文字</Title> </div> ); ``` ![](https://i.imgur.com/z32VweE.png) ## 巢狀(Nesting)語法 Styled-components 還支持使用 SCSS 語法,可以在巢狀結構內設定子組件的樣式,或是使用 ```&``` 字元添加 CSS 偽類。比如下面的程式碼,為 Title Component 加上 ```hover``` 樣式、以及針對內部的 ```span``` 子元素添加樣式: ```javascript= const Title = styled.h2` font-size: 20px; color: black; &:hover { color: blue; // <Title> when hovered } span { color: green; // style <span> in <Title> } `; ``` ```jsx= return ( <div> <RedTitle>標題文字</RedTitle> <Title> 標題<span>文字</span> </Title> </div> ); ``` ![](https://i.imgur.com/TD1v6BU.png) ## 小結 簡單的入門了 Styled-components,學會了一些基本的使用,現在我們就可以在 React 中定義元素的樣式。 如果文章中有錯誤的地方,要麻煩各位大大不吝賜教;喜歡的話,也要記得幫我按讚訂閱喔❤️ ### 參考資料 - [Styled Component - Document](https://styled-components.com/docs/basics#motivation)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully