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
    • 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 Versions and GitHub Sync Note Insights 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    ###### tags: `前端技能樹` # 網頁UI組件化 — React component >前情提要:在上一篇我們學習了如何在 React 使用 JSX 撰寫 Element 呈現出網頁頁面,接下來就會帶著大家將這些 React Element 抽離,建立 React 的核心 — Component,並且處理組件內部的資料。 ## 建立 React component 直接利用上一篇文章的 Codesandbox React 專案,我們會實作做一個簡單的計數器。在上篇文章的最後,提到 index.js 裡面的 ```<App />``` 就是一個 Component,組件的內容就實作在 app.js 裡。直接修改 app.js 內部的 React Element,呈現出計數器的畫面: App.js ```jsx= export default function App() { return ( <div className="App"> <h1>Member Score</h1> <div className="member"> <h2>May</h2> <h3>0</h3> <button>Plus</button> <button>Minus</button> </div> </div> ); } ``` ![](https://i.imgur.com/QOkZFRV.png) 組件的內容被包裹在函式內部,這被稱作是 Function Component。在 index.js 引入在別份程式碼 ```export``` 的 Component 後,就會接收它所回傳的 React Element 渲染在網頁上。 接著可以將記錄成員的資料和計數器的網頁元素抽離,新增 Member.js ,拆離上面的 ```member``` 區塊變成一個新的 Component。 Member.js ```jsx= export default function Member() { return ( <div className="member"> <h2>May</h2> <h3>0</h3> <button>Plus</button> <button>Minus</button> </div> ); } ``` 拆離 Component 並且將它 ```export``` 後,要做的事就是在 app.js 引入它。 ```jsx= import Member from "./Member"; export default function App() { return ( <div className="App"> <h1>Member Score</h1> <!-- 由使用者定義 component 的 element --> <Member /> </div> ); } ``` 我們**可以隨意將網頁內容劃分成無數個 Component,不過仍然要遵守拆解的原則,讓 Component 只會負責處理與該組件有關的事情**。另外你還可以將 Component 拆成更小 Component,比如 Member 內的計數器,就能抽離成 Counter Component。 Counter.js ```jsx= export default function Counter() { return ( <div className="counter"> <h3>0</h3> <button>Plus</button> <button>minus</button> </div> ); } ``` Member.js ```jsx= import Counter from "./Counter"; export default function Member() { return ( <div className="member"> <h2>May</h2> <Counter /> </div> ); } ``` ## 透過 Prop 傳遞組件資料 介面組件化的優點之一就是提升重複使用性,比如現在想要有三位成員的分數資料,只要複製三個 ```<Member />``` 組件,就可以呈現出同樣的畫面,**但同時三個組件會是獨立的,擁有各自的組件資料**。 App.js ```jsx= export default function App() { return ( <div className="App"> <h1>Member Score</h1> <Member /> <Member /> <Member /> </div> ); } ``` 但問題是,現在三個 Component 的名字都是 May,我們希望能夠顯示成員各自的名字。**React 就提供一個方法,可以將資料變成物件在 Component 間傳遞,這個物件就被稱作「props」**。舉例來說,只要在 ```<Member />``` 加上 ```name='名字'``` 屬性,```{name='名字'}``` 就會作為 props 傳入到 Member Component 內。 App.js ```jsx= export default function App() { return ( <div className="App"> <h1>Member Score</h1> <Member name='May'/> <Member name='Selina'/> <Member name='Julia'/> </div> ); } ``` 分別設定好每個組件 props 的值,直接在 Member Component 接收 props 變數使用,就能顯示出各自的名字。 Member.js ```jsx= import Counter from "./Counter"; export default function Member(props) { return ( <div className="member"> <h2>props.name</h2> <Counter /> </div> ); } ``` ![](https://i.imgur.com/HcrERLL.png) ## 加入 Local State 到組件 計數器的部分,兩個 Button 可以控制分數的加減,並且要讓Component 能夠記錄並更新分數,我們需要將分數存放到 State 中,當 ```render()``` 內部的 State 值更新,React 就會相對地更新網頁內容。 要在 Function Component 使用 State,會使用到 Hook 功能 ```useState```,它會回傳目前 state 數值,和可以讓你更新 State 的 Function,同時要設定初始值。 Counter.js ```jsx= import { useState } from "react"; export default function Counter() { //宣告一個 state 變數 score,初始值為 0 const [score, setScore] = useState(0); return ( <div className="Counter"> <h3>{score}</h3> ... </div> ); } ``` 現在要利用 ```useState``` 的 State Function,試著讓 State 隨著我們的輸入來更新。在兩個 Button 分別加上 Click 事件,按下 Plus 就讓計數器的值加一,按下 Minus 就減一: Counter.js ```jsx= export default function Counter() { ... return ( <div className="Counter"> ... <button onClick={() => setScore(score + 1)}>Plus</button> <button onClick={() => setScore(score - 1)}>minus</button> </div> ); } ``` 完成後試著按一按每個成員的計分器,你可以發現每個 Component 就能擁有自己的 State,分別成功記錄每位成員的分數。 ![](https://i.imgur.com/o0XjeFf.png) ## 小結 大致了解 React 最重要的核心 — Component,我們現在可以自定義網頁元件,並在組件內控制資料的處理。但 React 能做到的不會只有可將網頁介面拆成獨立的組件、提升重用性,下一個章節就再來探討 React 其他更便利的功能,包括條件 Render、生成列表,以及如何提升 Component 的資料層級。 [範例程式碼](https://codesandbox.io/s/21ithome-react2-osuh1) 如果文章中有錯誤的地方,要麻煩各位大大不吝賜教;喜歡的話,也要記得幫我按讚訂閱喔❤️ ### 參考資料 - [React Document](https://zh-hant.reactjs.org/docs/getting-started.html)

    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