🔍 搜尋結果:REACT

🔍 搜尋結果:REACT

36 個免費、漂亮的 React UI 模板與主題套件

網路上免費的 React 版型資源不太好找,最好有一份懶人包。 這份列表整理了各式各樣的模板與主題套件,希望對您有幫助。 - 原文出處:https://dev.to/davidepacilio/35-free-react-templates-and-themes-32ci --- ##1. Open ![](https://dev-to-uploads.s3.amazonaws.com/i/gy9nddokri1vobwrtbna.jpg) [**Live demo**](https://open.cruip.com/) / [**Download**](https://github.com/cruip/open-react-template) Open 是一個免費的 React 模板,專為開源專案、線上服務、數位產品,創建快速、專業的登陸頁面而生。為了吸引潛在客戶和電子郵件訂閱者,Open 提供了一個多功能的資源庫,其中包含時尚、簡約和可重複使用的元件和元素。 --- ##2. Atomize ![](https://dev-to-uploads.s3.amazonaws.com/i/ks2st96gb0tbu1ybuy6k.jpg) [**Live demo**](https://atomizecode.com/) / [**Download**](https://github.com/proksh/atomize) Atomize 是一個 React UI 框架,旨在幫助開發人員與設計師合作,輕鬆構建一致和諧的用戶界面。由於樣式指南和靈活網格等資源的完美結合,Atomize 適合建立任何類型的響應式網站。 --- ##3. Treact ![](https://dev-to-uploads.s3.amazonaws.com/i/3aw9a273jibs97o2l09m.jpg) [**Live demo**](https://treact.owaiskhan.me/) / [**Download**](https://gumroad.com/l/QaruQ) Treact 是使用 TailwindCSS 作為前端框架開發的現代 React 模板和 UI 組件展示庫。這個精美的檔案庫提供了 7 個內建的主頁、8 個輔助頁面以及 52 個預先設計的元素和段落。每個內容都可以針對家用電腦、平板電腦和移動設備進行擴充。 --- ##4. MatX ![](https://dev-to-uploads.s3.amazonaws.com/i/q99tvy2uvyvol2xet2et.jpg) [**Live demo**](http://matx-react.ui-lib.com/dashboard/analytics) / [**Download**](https://ui-lib.com/downloads/matx-react-dashboard/) MatX 是一個建立在 Material Design 之上的精美 React Native 模板。此模板使用 React、Redux 和 Material UI,它包含為 Web 應用程式提供新造型可能需要的所有基本功能。 MatX 的免費版本可用於輕鬆設置管理面板、用戶管理系統和專案管理系統。 --- ##5. Holly ![](https://dev-to-uploads.s3.amazonaws.com/i/dcrv1qxgo3rgq9a3j3at.jpg) [**Live demo**](https://lukemcdonald.github.io/holly-react/) / [**Download**](https://github.com/lukemcdonald/holly-react) Holly 是一個響應式 React JS 模板,適用於線上服務和數位產品的生產者,能在主要產品仍在開發中時,就開始搜集電子郵件地址。這個模板最初是由 [Cruip](https://cruip.com/) 用 HTML 設計的,然後在這個版本中用 React 撰寫。 --- ##6. OAH-Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/rteeixluj4n09a3s69ma.jpg) [**Live demo**](https://oah-admin.ahmedelywa.com/extra-components/progress/) / [**Download**](https://github.com/AhmedElywa/oah-admin) OAH-Admin 是一個基於 Gatsby 的免費 React 管理儀表板模板,帶有 oah-ui 元件和元素包。這個 React 模板有良好的 UI 元件色調,超級整潔和靈活的格式使任何人都可以輕鬆建立 SaaS 應用程式、管理面板、儀表板。 --- ##7. Gatsby Starter Ghost ![](https://dev-to-uploads.s3.amazonaws.com/i/ocey043yzsdt31f7yi9s.jpg) [**Live demo**](https://gatsby.ghost.org/) / [**Download**](https://github.com/TryGhost/gatsby-starter-ghost) 使用 Ghost 這個基於 Gatsby 的入門模板,輕鬆建立高效能網站。Gatsby Starter Ghost 是一個乾淨而現代的模板,適用於部落格、雜誌或任何新聞網站。該產品專門設計來幫助任何人在網路上建立個人空間並分享想法、創意和更新。 --- ##8. Star Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/hlbf4y4pl4a5od2c8chb.jpg) [**Live demo**](https://www.bootstrapdash.com/demo/star-admin-free/react/template/demo_1/preview/dashboard) / [**Download**](https://github.com/BootstrapDash/StarAdmin-Free-React-Admin-Template) 一個免費的 React Native 模板,提供了無窮無盡的各種基本元素,可以將任何想法變為現實。該模板具有精心製作的儀表板,包含大量整齊排列和組織的元件,它可以完美地與所有最新和現代的瀏覽器配合使用,並且能夠使資料可視化過程更易於管理。 --- ##9. Carolina Admin Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/05r7fsc1jzylez5diu6f.jpg) [**Live demo**](https://demo.uifort.com/carolina-react-admin-dashboard-material-ui-free-demo/LandingPage) / [**Download**](https://uifort.com/template/carolina-react-admin-dashboard-material-ui-free/) 如果您正在尋找一個令人驚嘆且實用的 React 儀表板模板,Carolina Admin Dashboard 擁有啟動和運行您 Web 專案所需的一切。這個漂亮的模板建立在 Material-UI 框架之上,採用乾淨清新的設計,遵循所有 Google 的 Material Design 指南。此外,核心結構是完全響應式和開源的。 --- ##10. Tabler ![](https://dev-to-uploads.s3.amazonaws.com/i/nu5vq6j5buk36iz8prsn.jpg) [**Live demo**](http://tabler-react.com/) / [**Download**](https://github.com/tabler/tabler-react) Tabler 是一個免費的 React 管理儀表板模板,非常適合任何類型的後端 Web 應用。此管理模板包含大量精心設計的範例,無需從頭開始,可為您節省大量時間,它還附帶可重複使用的元件,例如按鈕、地圖、圖表、表單等。 --- ##11. React Nice Resume ![](https://dev-to-uploads.s3.amazonaws.com/i/ci5hhvp6ki5o3mpk8zbz.jpg) [**Live demo**](https://nordicgiant2.github.io/react-nice-resume-page/#home) / [**Download**](https://github.com/nordicgiant2/react-nice-resume) React Nice Resume 是一個漂亮的主題,如果您是開發人員、設計師或一般的數位創作者,可以用來宣傳您自己和您的作品。該資源展示了一個獨特的主頁,帶有粒子背景、工作經驗時間線、技能圖表、顯示最新專案的縮略圖、一個帶有功能輸入表單的段落。 --- ##12. Boss Lite ![](https://dev-to-uploads.s3.amazonaws.com/i/zq92otm0bc9t3mwinkxb.jpg) [**Live demo**](http://boss.ux-maestro.com/app/tables/data-table) / [**Download**](https://github.com/ilhammeidi/boss-lite) Boss Lite 是一個基於 React 和 Redux 的管理儀表板模板。此模板為您帶來清新現代的設計和多種配色方案。它支援大多類型的 Web 專案,並且 Flexbox 佈局而變得很流暢。 --- ##13. Chakra UI ![](https://dev-to-uploads.s3.amazonaws.com/i/poootemj2t5caoi4lryt.jpg) [**Live demo**](https://chakra-ui.com/) / [**Download**](https://github.com/chakra-ui/chakra-ui/) Chakra UI 提供了一組好用、可重用的 React 功能元件,使建立好用網站和用戶界面變得非常簡單。 Chakra UI 中的幾乎所有元素都兼容深色模式,它們遵循 WAI-ARIA 指南規範,並構建在 React UI Primitive 之上以實現無限的可組合性。 --- ##14. Black Dashboard React ![](https://dev-to-uploads.s3.amazonaws.com/i/2r1tx4uxug6k1xlnr3pr.jpg) [**Live demo**](https://demos.creative-tim.com/black-dashboard-react/#/admin/dashboard) / [**Download**](https://www.creative-tim.com/product/black-dashboard-react) Black Dashboard React 是用於管理界面的 React 模板。該模板基於 Bootstrap 建立的設計指南,是基於企業的應用程式,是強大後端軟體可用的優秀前端選項。它具有更高等級的切分、設計套件、可重複使用的圖表,能夠不斷改善用戶和開發體驗。 --- ##15. Argon Design System ![](https://dev-to-uploads.s3.amazonaws.com/i/tvrfqzddf6kwmhiwje6x.jpg) [**Live demo**](https://demos.creative-tim.com/argon-design-system-react/) / [**Download**](https://github.com/creativetimofficial/argon-design-system-react) 使用 Bootstrap 4 和 Reactstrap 的 React 設計系統。Argon Design System 帶有 100 多個單獨的元件、內建的範例,並且每個元素都有多種樣式、懸停、焦點狀態,任何人都可以輕鬆使用。該產品是從原型設計到正式上線的完美解決方案。 --- ##16. Devias Kit - Admin Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/j7lqqfvgmujtgg1m80oi.jpg) [**Live demo**](https://react-material-dashboard.devias.io/dashboard) / [**Download**](https://github.com/devias-io/react-material-dashboard) Devias Kit 是一個響應式 Material Design 管理儀表板,專為 React 使用 Google 自己的 Material Design 框架建立。可以自定義設置、指令、圖標和樣式。該模板包含清晰直觀的目錄和文件、快速入門文件,如果您想對設計進行任何更改,甚至還有 Sketch 文件。 --- ##17. Dev Blog ![](https://dev-to-uploads.s3.amazonaws.com/i/1tym4ekzrftd6ldcflid.jpg) [**Live demo**](https://ryanfitzgerald.github.io/devblog/) / [**Download**](https://github.com/RyanFitzgerald/devblog) Dev Blog 是一個 React 網站模板,專為快速建立副專案和產品而生。該網站模板帶有一個首頁,其中顯示了部落格名稱、社交媒體圖示以及帶有文字和圖像的文章縮圖。該模板還包括單個文章頁面,有漂亮且精心策劃的排版。 --- ##18. Material PRO ![](https://dev-to-uploads.s3.amazonaws.com/i/scakf4swq5j99hln1xqx.jpg) [**Live demo**](https://wrappixel.com/demos/free-admin-templates/materialpro-reactadmin-lite/main/#/starter/starter) / [**Download**](https://www.wrappixel.com/templates/materialpro-react-admin-lite/) Material Pro 是一個免費的 React Native 模板,為任何需要管理儀表板的人精心製作。這個漂亮而清爽的產品採用模組化和現代設計理念開發,100% 免費使用和下載,並包含許多頁面,可幫助您更快、更輕鬆地建立專案。 --- ##19. Ant Design Landing ![](https://dev-to-uploads.s3.amazonaws.com/i/wnld469wyg4u9pfk31i1.jpg) [**Live demo**](https://landing.ant.design/) / [**Download**](https://github.com/ant-design/ant-design-landing) Landing 是 Ant Design System 建立的模板。內涵不同樣式的首頁和內頁模組。 --- ##20. Isomorphic ![](https://dev-to-uploads.s3.amazonaws.com/i/zy0at5stk267a06n5f95.jpg) [**Live demo**](https://isomorphic.redq.io/dashboard) / [**Download**](https://github.com/pujoey/ismorphic) Isomorphic 是一個易於管理且有吸引力的管理模板,具有大量靈活的元件。 --- ##21. Shards Dashboard Lite ![](https://dev-to-uploads.s3.amazonaws.com/i/71cn55agi3k9er11xk4o.jpg) [**Live demo**](https://designrevision.com/demo/shards-dashboard-lite-react/blog-overview) / [**Download**](https://designrevision.com/downloads/shards-dashboard-lite-react/) Shards 是一個免費的 React 儀表板模板,具有現代設計系統和許多自定義頁面和部分。 --- ##22. uiw ![](https://dev-to-uploads.s3.amazonaws.com/i/e6aakqf9m9g67mstwvi9.jpg) [**Live demo**](https://uiwjs.github.io/) / [**Download**](https://github.com/uiwjs/uiw) uiw 是用於 React 16+ 的高質量 React 元件庫和 UI 工具包。 --- ##23. React Material Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/te6tezfjcp008lb4q7du.jpg) [**Live demo**](https://flatlogic.github.io/react-material-admin/#/login) / [**Download**](https://flatlogic.com/templates/react-material-admin) React Material Admin 是一個建立在 Material-UI 框架之上的 React 儀表板。 --- ##24. Material KIT React ![](https://dev-to-uploads.s3.amazonaws.com/i/cq2xlu4tci8km6p2tia7.jpg) [**Live demo**](https://demos.creative-tim.com/material-kit-react/) / [**Download**](https://www.creative-tim.com/product/material-kit-react) Material UI KIT 是一款免費的 React UI 主題,其設計靈感來自 Google 的 Material Design,設計清新整潔。 --- ##25. Airframe ![](https://dev-to-uploads.s3.amazonaws.com/i/qwt4nv73xjn14a9g09yl.jpg) [**Live demo**](http://dashboards.webkom.co/react/airframe/dashboards/projects/) / [**Download**](https://github.com/0wczar/airframe-react) Airframe 是一個基於 Bootstrap 4 和 React 16 的免費開源 React 應用程式模板。 --- ##26. Gatsby Simplefolio ![](https://dev-to-uploads.s3.amazonaws.com/i/pe3clc53zqsntgh3vw3n.jpg) [**Live demo**](https://gatsby-simplefolio.netlify.app/) / [**Download**](https://github.com/cobidev/gatsby-simplefolio) Gatsby Simplefolio 是一個乾淨、美觀且響應迅速的 React 組合模板。 --- ##27. Ant Design Pro ![](https://dev-to-uploads.s3.amazonaws.com/i/diktnddjjf630tdyyqa8.jpg) [**Live demo**](https://pro.ant.design/) / [**Download**](https://github.com/ant-design/ant-design-pro/) React --- ##28. React SaaS Template ![](https://dev-to-uploads.s3.amazonaws.com/i/yiq5ast9jw3knt8l92l0.jpg) [**Live demo**](https://reactsaastemplate.com/) / [**Download**](https://github.com/dunky11/react-saas-template) --- ##29. Shards React ![](https://dev-to-uploads.s3.amazonaws.com/i/34zfg3e4qbbzklmgr4uh.jpg) [**Live demo**](https://designrevision.com/downloads/shards-react/) / [**Download**](https://github.com/designrevision/shards-react) --- ##30. Base Web ![](https://dev-to-uploads.s3.amazonaws.com/i/8q3bxpsll7k0qrhzdlmj.jpg) [**Live demo**](https://baseweb.design/) / [**Download**](https://github.com/uber/baseweb) --- ##31. Light Blue React Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/tfwzjgvh2sa8e5v9a0oa.jpg) [**Live demo**](https://demo.flatlogic.com/light-blue-react/#/app/main/dashboard) / [**Download**](https://github.com/flatlogic/light-blue-react-template) --- ##32. React JS Landing ![](https://dev-to-uploads.s3.amazonaws.com/i/ibuom994cxj3pzb2yzoz.jpg) [**Live demo**](https://react-landing-page-template.herokuapp.com/#page-top) / [**Download**](https://github.com/IssaafKattan/React-Landing-Page-Template) --- ##33. Admin Pro ![](https://dev-to-uploads.s3.amazonaws.com/i/0f1pjehgesa25ts39wx7.jpg) [**Live demo**](https://wrappixel.com/demos/free-admin-templates/adminpro-react-lite/main/#/dashboard) / [**Download**](https://www.wrappixel.com/templates/adminpro-react-admin-lite/#comparison) --- ##34. Blueprint ![](https://dev-to-uploads.s3.amazonaws.com/i/d1owpo8lfg3zfq1p2vpx.jpg) [**Live demo**](https://blueprintjs.com/) / [**Download**](https://github.com/palantir/blueprint) --- ##35. Datta ![](https://dev-to-uploads.s3.amazonaws.com/i/3con3tndvc7au5zg1jb0.jpg) [**Live demo**](http://lite.codedthemes.com/datta-able/react/default/dashboard/default) / [**Download**](https://codedthemes.com/item/datta-able-react-free-admin-template/) --- ##36. Flatlogic One ![](https://dev-to-uploads.s3.amazonaws.com/i/63flhvqcbh7jtfvih9do.jpg) [**Live demo**](https://flatlogic.github.io/one-react-template/#/login) / [**Download**](https://flatlogic.com/templates/one-free-react-template) --- ##結論 我希望這組免費的 React 模板和主題能夠幫助您!

經驗分享:Code Review 程式碼審查的藝術

程式碼審查很難。以下是一些心得分享。 - 原文出處:https://dev.to/saminarp/today-i-learned-the-subtle-art-of-code-reviews-3pef --- 我最近在審查 https://github.com/humphd/my-photohub 的一個 PR。 這是我有生以來第一次進行程式碼審查,也讓我知道這項任務有多麼困難。第一次當審閱者,我發現自己盯著程式碼,思考可以做些什麼來讓它更好。感覺相當迷茫。我想出了一些平庸的建議。沒想到什麼厲害的。沒有什麼讓我覺得很滿意的建議。然後是 Dave 教授 https://github.com/humphd 對我正在審查的同一個 PR 進行程式碼審查。我只是坐在那裡,對他看到而我沒看到的細節感到驚訝。他提出了一些大改善,比如更好的程式設計邏輯,以及一些小建議,比如更新專案描述。這些小建議我也可以提出:更好的專案描述、更適合專案的圖示而不是預設的 React 圖示、並為某些事情創建紀錄追蹤。為什麼我會忽略掉 Dave 教授如此優雅、毫不費力就指出的明顯事情? ## 一些程式碼審查的最佳實踐 這是一篇很棒的文章 https://google.github.io/eng-practices/review/reviewer/looking-for.html 我在研究程式碼審查最佳實踐時找到的。 它漂亮地闡述了設計、功能、複雜性、測試、命名、註釋、樣式、一致性、文檔和上下文都是代碼審查的重要組成。 ## 時間、注意力、溝通 好的審查需要時間和注意力。它需要我們批判性地思考程式設計邏輯。對於初學者來說,盯著別人寫的程式碼來建議一些有意義的東西,可能會讓人感到不知所措。害怕犯錯。害怕冒犯寫程式的人。我知道,因為這些我都有感受到。在開源專案中,在提供建設性回饋的同時,在溝通中保持禮貌和尊重很重要。我們有時可能不認同審查,這種時候,我們應該禮貌地溝通。 在給予和接受回饋時,保持開放的心態也很重要。正是通過這種思想交流和回饋,我們才能夠隨著時間一直進步。 如果你有一些寫程式經驗,只要花足夠的時間專心看程式碼,幾乎總是可以提出改進建議。 ## 從小處著手 如果您是初學者,請從小處著手並向他人學習。閱讀 Dave 教授的評論,我學到了很多重要的東西。然後我意識到,只有看到更有經驗的人如何審查程式碼,我才能變得更好。我記下了我在 GitHub 上閱讀他的大量評論所學到的東西。我把這些東西變成了清單: - 如果不清楚,請詢問有關某程式碼的具體問題。 - 找找看未使用的依賴項和優化 package.json 的方法。 - 從整個程式碼庫的上下文中來看事情。 - 留下一些鼓勵的話,指出開發人員做對了什麼! - 專注於功能和相容性。 - 找出清晰的命名和適當的命名約定。 - 查看 README 檔或 CONTRIBUTING.md 檔時,請看看樣式、格式、拼寫和語法的一致性。 - 確保設計和UI看起來不錯。 - 確保單元測試是為這段程式碼適當設計的。 - 確保程式碼符合提供的某個樣式指南。 ## `linters` 會帶給我們信任 程式碼自動檢查器和靜態工具分析器可以幫助審閱者節省大量時間在尋找愚蠢的拼寫錯誤或樣式錯誤。linters 和 sanners 的作用大概就是拼寫和語法檢查。省下了檢查格式和其他風格的麻煩,審閱者可以專注於程式碼的實際邏輯。作為程式碼審閱者,必須使用可用的自動代碼檢查器來節省時間和心思。 ## 關於生產力的最後一點想法 如果你像我一樣喜歡閱讀有關心理學和生產力的文章,這是一篇很棒的文章 https://jamesclear.com/focus#Focus%20on%20the%20Process

快速複習 React 基本觀念&實務範例:推薦新手參考

React 作為一個強大的前端工具,有很多需要熟悉的基本觀念&語法。 這篇文章做一個快速的全面整理,方便工作時,可以隨時翻閱,希望您喜歡。 - 原文出處:https://dev.to/reedbarger/the-react-cheatsheet-for-2020-real-world-examples-4hgg ## 核心概念 ### 元素和 JSX - React 元素的基本語法 ``` // In a nutshell, JSX allows us to write HTML in our JS // JSX can use any valid html tags (i.e. div/span, h1-h6, form/input, etc) <div>Hello React</div> ``` - JSX 元素就是一段表達式 ``` // as an expression, JSX can be assigned to variables... const greeting = <div>Hello React</div>; const isNewToReact = true; // ... or can be displayed conditionally function sayGreeting() { if (isNewToReact) { // ... or returned from functions, etc. return greeting; // displays: Hello React } else { return <div>Hi again, React</div>; } } ``` - JSX 允許我們嵌套表達式 ``` const year = 2020; // we can insert primitive JS values in curly braces: {} const greeting = <div>Hello React in {year}</div>; // trying to insert objects will result in an error ``` - JSX 允許我們嵌套元素 ``` // to write JSX on multiple lines, wrap in parentheses: () const greeting = ( // div is the parent element <div> {/* h1 and p are child elements */} <h1>Hello!</h1> <p>Welcome to React</p> </div> ); // 'parents' and 'children' are how we describe JSX elements in relation // to one another, like we would talk about HTML elements ``` - HTML 和 JSX 的語法略有不同 ``` // Empty div is not <div></div> (HTML), but <div/> (JSX) <div/> // A single tag element like input is not <input> (HTML), but <input/> (JSX) <input name="email" /> // Attributes are written in camelcase for JSX (like JS variables <button className="submit-button">Submit</button> // not 'class' (HTML) ``` - 最基本的 React 應用程式需要三樣東西: - 1. ReactDOM.render() 渲染我們的應用程序 - 2. 一個 JSX 元素(在此情況下,稱為根節點) - 3. 一個用於掛載應用程式的 DOM 元素(通常是 index.html 文件中 id 為 root 的 div) ``` // imports needed if using NPM package; not if from CDN links import React from "react"; import ReactDOM from "react-dom"; const greeting = <h1>Hello React</h1>; // ReactDOM.render(root node, mounting point) ReactDOM.render(greeting, document.getElementById("root")); ``` ### 元件和 Props - 基本 React 元件的語法 ``` import React from "react"; // 1st component type: function component function Header() { // function components must be capitalized unlike normal JS functions // note the capitalized name here: 'Header' return <h1>Hello React</h1>; } // function components with arrow functions are also valid const Header = () => <h1>Hello React</h1>; // 2nd component type: class component // (classes are another type of function) class Header extends React.Component { // class components have more boilerplate (with extends and render method) render() { return <h1>Hello React</h1>; } } ``` - 如何使用元件 ``` // do we call these function components like normal functions? // No, to execute them and display the JSX they return... const Header = () => <h1>Hello React</h1>; // ...we use them as 'custom' JSX elements ReactDOM.render(<Header />, document.getElementById("root")); // renders: <h1>Hello React</h1> ``` - 元件可以在我們的應用程式中重複使用 ``` // for example, this Header component can be reused in any app page // this component shown for the '/' route function IndexPage() { return ( <div> <Header /> <Hero /> <Footer /> </div> ); } // shown for the '/about' route function AboutPage() { return ( <div> <Header /> <About /> <Testimonials /> <Footer /> </div> ); } ``` - 資料可以通過 props 動態傳遞給元件 ``` // What if we want to pass data to our component from a parent? // I.e. to pass a user's name to display in our Header? const username = "John"; // we add custom 'attributes' called props ReactDOM.render( <Header username={username} />, document.getElementById("root") ); // we called this prop 'username', but can use any valid JS identifier // props is the object that every component receives as an argument function Header(props) { // the props we make on the component (i.e. username) // become properties on the props object return <h1>Hello {props.username}</h1>; } ``` - Props 不可直接改變(mutate) ``` // Components must ideally be 'pure' functions. // That is, for every input, we be able to expect the same output // we cannot do the following with props: function Header(props) { // we cannot mutate the props object, we can only read from it props.username = "Doug"; return <h1>Hello {props.username}</h1>; } // But what if we want to modify a prop value that comes in? // That's where we would use state (see the useState section) ``` - 如果我們想將元素/元件作為 props 傳遞給其它元件,可以用 children props ``` // Can we accept React elements (or components) as props? // Yes, through a special property on the props object called 'children' function Layout(props) { return <div className="container">{props.children}</div>; } // The children prop is very useful for when you want the same // component (such as a Layout component) to wrap all other components: function IndexPage() { return ( <Layout> <Header /> <Hero /> <Footer /> </Layout> ); } // different page, but uses same Layout component (thanks to children prop) function AboutPage() { return ( <Layout> <About /> <Footer /> </Layout> ); } ``` - 可以用三元運算子來條件顯示元件 ``` // if-statements are fine to conditionally show , however... // ...only ternaries (seen below) allow us to insert these conditionals // in JSX, however function Header() { const isAuthenticated = checkAuth(); return ( <nav> <Logo /> {/* if isAuth is true, show AuthLinks. If false, Login */} {isAuthenticated ? <AuthLinks /> : <Login />} {/* if isAuth is true, show Greeting. If false, nothing. */} {isAuthenticated && <Greeting />} </nav> ); } ``` - Fragments 是用來顯示多個元件的特殊元件,無需向 DOM 添加額外的元素 - Fragments 適合用在條件邏輯 ``` // we can improve the logic in the previous example // if isAuthenticated is true, how do we display both AuthLinks and Greeting? function Header() { const isAuthenticated = checkAuth(); return ( <nav> <Logo /> {/* we can render both components with a fragment */} {/* fragments are very concise: <> </> */} {isAuthenticated ? ( <> <AuthLinks /> <Greeting /> </> ) : ( <Login /> )} </nav> ); } ``` ### 列表和 keys - 使用 .map() 將資料列表(陣列)轉換為元素列表 ``` const people = ["John", "Bob", "Fred"]; const peopleList = people.map(person => <p>{person}</p>); ``` - .map() 也可用來轉換為元件列表 ``` function App() { const people = ['John', 'Bob', 'Fred']; // can interpolate returned list of elements in {} return ( <ul> {/* we're passing each array element as props */} {people.map(person => <Person name={person} />} </ul> ); } function Person({ name }) { // gets 'name' prop using object destructuring return <p>this person's name is: {name}</p>; } ``` - 迭代的每個 React 元素都需要一個特殊的 `key` prop - key 對於 React 來說是必須的,以便能夠追蹤每個正在用 map 迭代的元素 - 沒有 key,當資料改變時,React 較難弄清楚元素應該如何更新 - key 應該是唯一值,才能讓 React 知道如何分辨 ``` function App() { const people = ['John', 'Bob', 'Fred']; return ( <ul> {/* keys need to be primitive values, ideally a generated id */} {people.map(person => <Person key={person} name={person} />)} </ul> ); } // If you don't have ids with your set of data or unique primitive values, // you can use the second parameter of .map() to get each elements index function App() { const people = ['John', 'Bob', 'Fred']; return ( <ul> {/* use array element index for key */} {people.map((person, i) => <Person key={i} name={person} />)} </ul> ); } ``` ### 事件和事件處理器 - React 和 HTML 中的事件略有不同 ``` // Note: most event handler functions start with 'handle' function handleToggleTheme() { // code to toggle app theme } // in html, onclick is all lowercase <button onclick="handleToggleTheme()"> Submit </button> // in JSX, onClick is camelcase, like attributes / props // we also pass a reference to the function with curly braces <button onClick={handleToggleTheme}> Submit </button> ``` - 最該先學的 React 事件是 onClick 和 onChange - onClick 處理 JSX 元素上的點擊事件(也就是按鈕動作) - onChange 處理鍵盤事件(也就是打字動作) ``` function App() { function handleChange(event) { // when passing the function to an event handler, like onChange // we get access to data about the event (an object) const inputText = event.target.value; const inputName = event.target.name; // myInput // we get the text typed in and other data from event.target } function handleSubmit() { // on click doesn't usually need event data } return ( <div> <input type="text" name="myInput" onChange={handleChange} /> <button onClick={handleSubmit}>Submit</button> </div> ); } ``` ## React Hooks ### State and useState - useState 為我們提供 function component 中的本地狀態 ``` import React from 'react'; // create state variable // syntax: const [stateVariable] = React.useState(defaultValue); function App() { const [language] = React.useState('javascript'); // we use array destructuring to declare state variable return <div>I am learning {language}</div>; } ``` - 注意:此段文章中的任何 hook 都來自 React 套件,且可以單獨導入 ``` import React, { useState } from "react"; function App() { const [language] = useState("javascript"); return <div>I am learning {language}</div>; } ``` - useState 還為我們提供了一個 `setter` 函數來更新它的狀態 ``` function App() { // the setter function is always the second destructured value const [language, setLanguage] = React.useState("python"); // the convention for the setter name is 'setStateVariable' return ( <div> {/* why use an arrow function here instead onClick={setterFn()} ? */} <button onClick={() => setLanguage("javascript")}> Change language to JS </button> {/* if not, setLanguage would be called immediately and not on click */} <p>I am now learning {language}</p> </div> ); } // note that whenever the setter function is called, the state updates, // and the App component re-renders to display the new state ``` - useState 可以在單個元件中使用一次或多次 ``` function App() { const [language, setLanguage] = React.useState("python"); const [yearsExperience, setYearsExperience] = React.useState(0); return ( <div> <button onClick={() => setLanguage("javascript")}> Change language to JS </button> <input type="number" value={yearsExperience} onChange={event => setYearsExperience(event.target.value)} /> <p>I am now learning {language}</p> <p>I have {yearsExperience} years of experience</p> </div> ); } ``` - useState 可以接受 primitive value 或物件 ``` // we have the option to organize state using whatever is the // most appropriate data type, according to the data we're tracking function App() { const [developer, setDeveloper] = React.useState({ language: "", yearsExperience: 0 }); function handleChangeYearsExperience(event) { const years = event.target.value; // we must pass in the previous state object we had with the spread operator setDeveloper({ ...developer, yearsExperience: years }); } return ( <div> {/* no need to get prev state here; we are replacing the entire object */} <button onClick={() => setDeveloper({ language: "javascript", yearsExperience: 0 }) } > Change language to JS </button> {/* we can also pass a reference to the function */} <input type="number" value={developer.yearsExperience} onChange={handleChangeYearsExperience} /> <p>I am now learning {developer.language}</p> <p>I have {developer.yearsExperience} years of experience</p> </div> ); } ``` - 如果新狀態依賴於之前的狀態,我們可以在 setter 函數中使用一個函數來為我們提供之前狀態的值 ``` function App() { const [developer, setDeveloper] = React.useState({ language: "", yearsExperience: 0, isEmployed: false }); function handleToggleEmployment(event) { // we get the previous state variable's value in the parameters // we can name 'prevState' however we like setDeveloper(prevState => { return { ...prevState, isEmployed: !prevState.isEmployed }; // it is essential to return the new state from this function }); } return ( <button onClick={handleToggleEmployment}>Toggle Employment Status</button> ); } ``` ### side effects 和 useEffect - useEffect 讓我們在 function component 中執行副作用。什麼是副作用? - 副作用是我們需要接觸外部世界的地方。例如,從 API 獲取資料或操作 DOM。 - 副作用是可能以不可預測的方式,改變我們元件狀態的操作(導致「副作用」)。 - useEffect 接受 callback function(稱為 effect 函數),預設情況下,每次重新渲染時都會運行 - useEffect 在我們的元件載入後運行,可以準確在元件的各個生命週期觸發 ``` // what does our code do? Picks a color from the colors array // and makes it the background color function App() { const [colorIndex, setColorIndex] = React.useState(0); const colors = ["blue", "green", "red", "orange"]; // we are performing a 'side effect' since we are working with an API // we are working with the DOM, a browser API outside of React useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; }); // whenever state is updated, App re-renders and useEffect runs function handleChangeIndex() { const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1; setColorIndex(next); } return <button onClick={handleChangeIndex}>Change background color</button>; } ``` - 如果不想在每次渲染後都執行 callback function,可以在第二個參數傳一個空陣列 ``` function App() { ... // now our button doesn't work no matter how many times we click it... useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; }, []); // the background color is only set once, upon mount // how do we not have the effect function run for every state update... // but still have it work whenever the button is clicked? return ( <button onClick={handleChangeIndex}> Change background color </button> ); } ``` - useEffect 讓我們能夠在 dependencies 陣列的內容改變時,才執行 - dependencies 陣列是第二個參數,如果陣列中的任何一個值發生變化,effect function 將再次運行 ``` function App() { const [colorIndex, setColorIndex] = React.useState(0); const colors = ["blue", "green", "red", "orange"]; // we add colorIndex to our dependencies array // when colorIndex changes, useEffect will execute the effect fn again useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; // when we use useEffect, we must think about what state values // we want our side effect to sync with }, [colorIndex]); function handleChangeIndex() { const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1; setColorIndex(next); } return <button onClick={handleChangeIndex}>Change background color</button>; } ``` - 可以在 useEffect 最後回傳一個函數,來取消訂閱某些效果 ``` function MouseTracker() { const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 }); React.useEffect(() => { // .addEventListener() sets up an active listener... window.addEventListener("mousemove", handleMouseMove); // ...so when we navigate away from this page, it needs to be // removed to stop listening. Otherwise, it will try to set // state in a component that doesn't exist (causing an error) // We unsubscribe any subscriptions / listeners w/ this 'cleanup function' return () => { window.removeEventListener("mousemove", handleMouseMove); }; }, []); function handleMouseMove(event) { setMousePosition({ x: event.pageX, y: event.pageY }); } return ( <div> <h1>The current mouse position is:</h1> <p> X: {mousePosition.x}, Y: {mousePosition.y} </p> </div> ); } // Note: we could extract the reused logic in the callbacks to // their own function, but I believe this is more readable ``` - 使用 useEffect 撈取資料 - 請注意,如果要使用更簡潔的 async/awit 語法處理 promise,則需要建立一個單獨的函數(因為 effect callback function 不能是 async) ``` const endpoint = "https://api.github.com/users/codeartistryio"; // with promises: function App() { const [user, setUser] = React.useState(null); React.useEffect(() => { // promises work in callback fetch(endpoint) .then(response => response.json()) .then(data => setUser(data)); }, []); } // with async / await syntax for promise: function App() { const [user, setUser] = React.useState(null); // cannot make useEffect callback function async React.useEffect(() => { getUser(); }, []); // instead, use async / await in separate function, then call // function back in useEffect async function getUser() { const response = await fetch("https://api.github.com/codeartistryio"); const data = await response.json(); setUser(data); } } ``` ### 效能和 useCallback - useCallback 是一個用來提高元件性能的 hook - 如果你有一個經常重新渲染的元件,useCallback 可以防止元件內的 callback function 在每次元件重新渲染時都重新創建(導致元件重新運行) - useCallback 僅在其依賴項之一改變時重新運行 ``` // in Timer, we are calculating the date and putting it in state a lot // this results in a re-render for every state update // we had a function handleIncrementCount to increment the state 'count'... function Timer() { const [time, setTime] = React.useState(); const [count, setCount] = React.useState(0); // ... but unless we wrap it in useCallback, the function is // recreated for every single re-render (bad performance hit) // useCallback hook returns a callback that isn't recreated every time const inc = React.useCallback( function handleIncrementCount() { setCount(prevCount => prevCount + 1); }, // useCallback accepts a second arg of a dependencies array like useEffect // useCallback will only run if any dependency changes (here it's 'setCount') [setCount] ); React.useEffect(() => { const timeout = setTimeout(() => { const currentTime = JSON.stringify(new Date(Date.now())); setTime(currentTime); }, 300); return () => { clearTimeout(timeout); }; }, [time]); return ( <div> <p>The current time is: {time}</p> <p>Count: {count}</p> <button onClick={inc}>+</button> </div> ); } ``` ### Memoization 和 useMemo - useMemo 和 useCallback 非常相似,都是為了提高效能。但就不是為了暫存 callback function,而是為了暫存耗費效能的運算結果 - useMemo 允許我們「記憶」已經為某些輸入進行了昂貴計算的結果(之後就不用重新計算了) - useMemo 從計算中回傳一個值,而不是 callback 函數(但可以是一個函數) ``` // useMemo is useful when we need a lot of computing resources // to perform an operation, but don't want to repeat it on each re-render function App() { // state to select a word in 'words' array below const [wordIndex, setWordIndex] = useState(0); // state for counter const [count, setCount] = useState(0); // words we'll use to calculate letter count const words = ["i", "am", "learning", "react"]; const word = words[wordIndex]; function getLetterCount(word) { // we mimic expensive calculation with a very long (unnecessary) loop let i = 0; while (i < 1000000) i++; return word.length; } // Memoize expensive function to return previous value if input was the same // only perform calculation if new word without a cached value const letterCount = React.useMemo(() => getLetterCount(word), [word]); // if calculation was done without useMemo, like so: // const letterCount = getLetterCount(word); // there would be a delay in updating the counter // we would have to wait for the expensive function to finish function handleChangeIndex() { // flip from one word in the array to the next const next = wordIndex + 1 === words.length ? 0 : wordIndex + 1; setWordIndex(next); } return ( <div> <p> {word} has {letterCount} letters </p> <button onClick={handleChangeIndex}>Next word</button> <p>Counter: {count}</p> <button onClick={() => setCount(count + 1)}>+</button> </div> ); } ``` ### Refs 和 useRef - Refs 是所有 React 組件都可用的特殊屬性。允許我們在元件安裝時,創建針對特定元素/元件的引用 - useRef 允許我們輕鬆使用 React refs - 我們在元件開頭呼叫 useRef,並將回傳值附加到元素的 ref 屬性來引用它 - 一旦我們創建了一個引用,就可以用它來改變元素的屬性,或者可以呼叫該元素上的任何可用方法(比如用 .focus() 來聚焦) ``` function App() { const [query, setQuery] = React.useState("react hooks"); // we can pass useRef a default value // we don't need it here, so we pass in null to ref an empty object const searchInput = useRef(null); function handleClearSearch() { // current references the text input once App mounts searchInput.current.value = ""; // useRef can store basically any value in its .current property searchInput.current.focus(); } return ( <form> <input type="text" onChange={event => setQuery(event.target.value)} ref={searchInput} /> <button type="submit">Search</button> <button type="button" onClick={handleClearSearch}> Clear </button> </form> ); } ``` ## 進階 Hook ### Context 和 useContext - 在 React 中,盡量避免創建多個 props 來將資料從父元件向下傳遞兩個或多個層級 ``` // Context helps us avoid creating multiple duplicate props // This pattern is also called props drilling: function App() { // we want to pass user data down to Header const [user] = React.useState({ name: "Fred" }); return ( // first 'user' prop <Main user={user} /> ); } const Main = ({ user }) => ( <> {/* second 'user' prop */} <Header user={user} /> <div>Main app content...</div> </> ); const Header = ({ user }) => <header>Welcome, {user.name}!</header>; ``` - Context 有助於將 props 從父組件向下傳遞到多個層級的子元件 ``` // Here is the previous example rewritten with Context // First we create context, where we can pass in default values const UserContext = React.createContext(); // we call this 'UserContext' because that's what data we're passing down function App() { // we want to pass user data down to Header const [user] = React.useState({ name: "Fred" }); return ( {/* we wrap the parent component with the provider property */} {/* we pass data down the computer tree w/ value prop */} <UserContext.Provider value={user}> <Main /> </UserContext.Provider> ); } const Main = () => ( <> <Header /> <div>Main app content...</div> </> ); // we can remove the two 'user' props, we can just use consumer // to consume the data where we need it const Header = () => ( {/* we use this pattern called render props to get access to the data*/} <UserContext.Consumer> {user => <header>Welcome, {user.name}!</header>} </UserContext.Consumer> ); ``` - useContext hook 可以移除這種看起來很怪的 props 渲染模式,同時又能在各種 function component 中隨意使用 ``` const Header = () => { // we pass in the entire context object to consume it const user = React.useContext(UserContext); // and we can remove the Consumer tags return <header>Welcome, {user.name}!</header>; }; ``` ### Reducers 和 useReducer - Reducers 是簡單、可預測的(純)函數,它接受一個先前的狀態物件和一個動作物件,並回傳一個新的狀態物件。例如: ``` // let's say this reducer manages user state in our app: function reducer(state, action) { // reducers often use a switch statement to update state // in one way or another based on the action's type property switch (action.type) { // if action.type has the string 'LOGIN' on it case "LOGIN": // we get data from the payload object on action return { username: action.payload.username, isAuth: true }; case "SIGNOUT": return { username: "", isAuth: false }; default: // if no case matches, return previous state return state; } } ``` - Reducers 是一種強大的狀態管理模式,用於流行的 Redux 狀態管理套件(這套很常與 React 一起使用) - 與 useState(用於本地元件狀態)相比,Reducers 可以通過 useReducer hook 在 React 中使用,以便管理我們應用程序的狀態 - useReducer 可以與 useContext 配對來管理資料並輕鬆地將資料傳遞給元件 - useReducer + useContext 可以當成應用程式的整套狀態管理系統 ``` const initialState = { username: "", isAuth: false }; function reducer(state, action) { switch (action.type) { case "LOGIN": return { username: action.payload.username, isAuth: true }; case "SIGNOUT": // could also spread in initialState here return { username: "", isAuth: false }; default: return state; } } function App() { // useReducer requires a reducer function to use and an initialState const [state, dispatch] = useReducer(reducer, initialState); // we get the current result of the reducer on 'state' // we use dispatch to 'dispatch' actions, to run our reducer // with the data it needs (the action object) function handleLogin() { dispatch({ type: "LOGIN", payload: { username: "Ted" } }); } function handleSignout() { dispatch({ type: "SIGNOUT" }); } return ( <> Current user: {state.username}, isAuthenticated: {state.isAuth} <button onClick={handleLogin}>Login</button> <button onClick={handleSignout}>Signout</button> </> ); } ``` ### 編寫 custom hooks - 創建 hook 就能輕鬆在元件之間重用某些行為 - hook 是一種比以前的 class component 更容易理解的模式,例如 higher-order components 或者 render props - 根據需要,隨時可以自創一些 hook ``` // here's a custom hook that is used to fetch data from an API function useAPI(endpoint) { const [value, setValue] = React.useState([]); React.useEffect(() => { getData(); }, []); async function getData() { const response = await fetch(endpoint); const data = await response.json(); setValue(data); }; return value; }; // this is a working example! try it yourself (i.e. in codesandbox.io) function App() { const todos = useAPI("https://todos-dsequjaojf.now.sh/todos"); return ( <ul> {todos.map(todo => <li key={todo.id}>{todo.text}</li>)} </ul> ); } ``` ### Hooks 規則 - 使用 React hooks 有兩個核心規則,要遵守才能正常運作: - 1. Hooks 只能在元件開頭呼叫 - Hooks 不能放在條件、迴圈或嵌套函數中 - 2. Hooks只能在 function component 內部使用 - Hooks 不能放在普通的 JavaScript 函數或 class component 中 ``` function checkAuth() { // Rule 2 Violated! Hooks cannot be used in normal functions, only components React.useEffect(() => { getUser(); }, []); } function App() { // this is the only validly executed hook in this component const [user, setUser] = React.useState(null); // Rule 1 violated! Hooks cannot be used within conditionals (or loops) if (!user) { React.useEffect(() => { setUser({ isAuth: false }); // if you want to conditionally execute an effect, use the // dependencies array for useEffect }, []); } checkAuth(); // Rule 1 violated! Hooks cannot be used in nested functions return <div onClick={() => React.useMemo(() => doStuff(), [])}>Our app</div>; } ``` --- 以上是快速整理,希望對您有幫助!

簡單介紹一下 NextJS 框架

Next.js 是一個開源、輕量的 JavaScript 框架。它讓您能用 React 開發高速又好用的 Web 應用程式與靜態網站。 這篇文章簡單介紹一下這個框架! - 原文出處:https://dev.to/documatic/why-use-nextjs-mn3 # 簡介 Next.js 是用來建造 server-side rendering 的 web 應用程式的 ReactJS 框架。包含很多現成功能,例如程式碼自動拆分、基於檔案的路由、hot reloading 和通用渲染。 https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0oqlfzpvx0rkns65juxt.png Next.js 會在 React 之外處理好工具、設定,並額外提供架構、功能、與效能優化。 Next.js 由 Vercel 的軟體工程師 Guillermo Rauch 打造,並由 Vercel 的開發團隊維護。它是一個開源專案,可以在 GitHub 上找到程式碼。 # Next.js 是做什麼用的? Next.JS 常用來建造以下類型的網站: - 電子商務網站 - 部落格 - 投資組合網站 - 文件網站 - 行銷網站等等 # Next.js 和 React.js 的區別 Next.js 和 React 都是建造 Web 應用程式的常用工具。但是,它們之間有明顯差異,適用不同場景。以下分別討論幾點: # 效能 性能是 Next.js 和 React.js 之間的主要區別。 Next.js 內建許多效能優化,例如圖像優化。這些優化使 Next.js 網站跑起來非常快。 另一方面,ReactJS 是在客戶端渲染,對於高性能應用程式來說,就不太夠力。 # SEO 靜態網站比較適合 SEO 優化,使用 Next.js 很容易做出靜態網站。SEO 越好,在搜尋結果越前面。 而 React 因為是渲染 singe page application,對 SEO 來說就比較吃虧。 # Server-side rendering Next.js 提供伺服器端渲染功能 (SSR)。當您需要為不同用戶提供不同渲染方式,它可以撈資料然後回應不同請求。 雖然可以啟用,但 React 預設不支援伺服器端渲染。SSR 可以與一些伺服器軟體整合,但需要一些額外作業。 # 開發者社群 React 社群很活躍、資源很多。 Next.js 大部份討論都在 GitHub 上面。 React.JS 和 Next.JS 都有很好的開發者體驗。 # 設定檔 使用 Create React App 的話,記得要跳出來才能獨立設定各項設定檔。 使用 Next.js 的話,可以在 Next.js 模板直接自訂 `babelrc`、`jest.config` 和 `eslintrc` 等文件。 # 結論 簡單介紹一下 Next.js ,希望對您有幫助!

React 生態系中,5個比較少見,但很好用的套件

我很喜歡在 NPM 目錄到處逛、尋找優質小套件。今天跟你分享五個我的近期發現! - 原文出處:https://dev.to/naubit/5-small-and-hidden-react-libraries-you-should-already-be-using-nb5 ## 1. Urlcat Urlcat 是一個小型的 Javascript 套件,可以非常方便地建立 URL、預防常見錯誤。 你當然可以直接用 URL API 來建立網址,但這種做法需要你手動處理一些細節。 Urlcat 就方便多了,隨插即用,不用花一堆時間讀文件,就能直接開始用。 https://github.com/balazsbotond/urlcat ## 2. UseHooks-ts ![](https://imgur.com/n7DL06Z.png) 如果你是 React 開發者、有在用 hook,很多時候你需要替一大堆小東西寫 custom hook。像是處理深色模式、處理視窗大小變化事件,等等。 UseHooks 是一個小套件,針對各種小案例都有現成的 hook,而且文件齊全、支援 TypeScript。 https://github.com/juliencrn/usehooks-ts ## 3. Logt ![](https://imgur.com/PU6eNCJ.gif) 我喜歡到處都有日誌,當需要知道發生了什麼時,就可以檢查。 當我寫前端時,**我也想要那些日誌**。但有一些先決條件: - 必須有完整的型別(這樣我就可以在 Typescript 中方便使用) - 必須很小 - 必須有彩色標籤(所以我很快就知道日誌類型) - 必須有分日誌級別 - 必須有一些方法,可以根據條件隱藏一些日誌(比如是否在正式環境) - 必須可以將這些日誌發送到其他地方(比如 Sentry) 經過大量時間研究(我都快自己開始寫了)我找到了 Logt,**它滿足我的所有要求**。 100% 推薦! https://github.com/sidhantpanda/logt ## 4. Loadable Components ![](https://imgur.com/H6eoKeF.png) 如果你正在嘗試優化 React 應用程式,**你可能正在使用 React.lazy** 和 Suspense 來延遲載入元件。 雖然也是可以,但還有更好的方法!比如這個套件。我無法在此完整說明原因,但請參考以下比較: https://loadable-components.com/docs/loadable-vs-react-lazy/ 基本上,它支持 **SSR**(_Server Side Rendering_)、**Library Splitting**,甚至 **完全動態導入**。還不錯吧? 此外,它真的很容易使用。**幾乎即插即用。**所以,試試吧! https://github.com/gregberge/loadable-components ## 5. Emoji Mart ![](https://imgur.com/jBA63Iu.png) 在處理不同的專案時,**我總是要處理表情符號。**現在到處都在使用它。而且我通常必須在專案中添加一些表情符號選擇器元件。 這還不算難。但是隨後開始收到更多要求:它必須**延遲載入表情符號**,它必須支持**國際化**,它必須允許**搜尋**,它必須允許使用**與 slack 相同的查詢縮寫**… 這些是可以做,但還是花時間在專案本身比較好吧。 所以,來使用 Emoji Mart 吧! https://github.com/missive/emoji-mart --- 以上是五個好用但是還不知名的小套件,希望你喜歡!

如何在 React 中漂亮地 render 一個列表:四點注意事項

面試的時候,常常會被問到這題。看似簡單,其實有一些進階注意事項,此篇與您分享。 - 原文出處:https://dev.to/andyrewlee/stand-out-in-a-react-interview-by-rendering-a-list-like-a-pro-1cn5 # 基本做法 以下是最基本做法。根據陣列內容,直接渲染成一個列表。 ``` import { useState, useEffect } from "react"; const App = () => { const [posts, setPosts] = useState([]); const [currentPost, setCurrentPost] = useState(undefined); useEffect(() => { const initialize = async () => { const res = await fetch("https://jsonplaceholder.typicode.com/posts"); const json = await res.json(); setPosts(json); }; initialize(); }, []); const onPostClick = (post) => { setCurrentPost(post); }; return ( <div> {currentPost && <h1>{currentPost.title}</h1>} <PostList posts={posts} onPostClick={onPostClick} /> </div> ); }; const PostList = ({ posts, onPostClick }) => { return ( <div> {posts.map((post) => ( <Post post={post} onPostClick={onPostClick} /> ))} </div> ); }; const Post = ({ post, onPostClick }) => { const onClick = () => { onPostClick(post); }; return <div onClick={onClick}>{post.title}</div>; }; export default App; ``` # 改進方法 以下是四個可以改進的方向,以及背後的原因。 ## 1. 指定 key 替每個元件提供一個 key 屬性,可以幫助後續 React 渲染時改善效能。要注意 key 屬性要是唯一值,不要直接用陣列索引當成 key。 ``` {posts.map((post) => ( <Post key={post.id} post={post} onPostClick={onPostClick} /> ))} ``` ## 2. 優化渲染 每次點擊列表項目時,都會重新渲染 `PostList` 和每個 `Post`。 ``` const Post = ({ post, onPostClick }) => { console.log("post rendered"); const onClick = () => { onPostClick(post); }; return <div onClick={onClick}>{post}</div>; }; ``` 可以使用 React 提供的 `memo` 功能來優化 `PostList` 元件。用 `memo` 包裝元件時,等於告訴 React:除非 props 改變,否則不要重新渲染這個元件。 ``` import { useState, useEffect, memo } from "react"; const PostList = memo(({ posts, onPostClick }) => { return ( <div> {posts.map((post) => ( <Post post={post} onPostClick={onPostClick} /> ))} </div> ); }); ``` 不過,實際跑下去,會發現還是重新渲染了。因為每次 currentPost 改變時,App 都會重新渲染。每次重新渲染都會重新建立 onPostClick 函數。當一個函數被重新建立時(即使函式內容一樣),都算是新的實體。所以技術上來說,props 確實發生了變化,所以 `PostList` 會重新渲染。 ``` const fn1 = () => {}; const fn2 = () => {}; fn1 === fn2; // => false ``` 這種狀況,就可以使用 useCallback hook 來告訴 React 不要重新建立函數。 ``` const onPostClick = useCallback((post) => { setCurrentPost(post); }, []); ``` 上面的例子中,使用 useCallback 沒問題,可以避免全部貼文被重新渲染。但要知道的是,並非什麼函式都適合包在 useCallback 裡面。 ``` const Post = ({ post, onPostClick }) => { const useCalllback(onClick = () => { onPostClick(post); }, []); return <div onClick={onClick}>{post.title}</div>; }; ``` 比方說,在 Post 元件使用 useCallback 就不太有意義。因為這個元件是輕量級的。應該只在有意義的情況下使用 useCallback(可以用 profiling 工具分析效能確認)。`useCallback` 有缺點:它增加了程式碼的複雜性。使用 useCallback 會在每次渲染時運行的額外程式碼。 ## 3. 元件卸載時清理乾淨 目前的元件沒有在卸載時進行清理。例如,如果在收到 URL 回應結果之前就離開頁面怎麼辦?這時應該要取消請求。 ``` useEffect(() => { const initialize = async () => { const res = await fetch("https://jsonplaceholder.typicode.com/posts"); const json = await res.json(); setPosts(json); }; initialize(); }, []); ``` `useEffect` 可以分為兩部分:掛載時運行的程式碼、卸載時運行的程式碼: ``` useEffect(() => { // When component mounts what code should I run? return () => { // When component unmounts what code should I run (clean up)? }; }, []); ``` 我們可以使用 AbortController ,並在清理時呼叫 controller.abort() 來取消請求。 ``` useEffect(() => { const controller = new AbortController(); const signal = controller.signal; const initialize = async () => { try { const res = await fetch("https://jsonplaceholder.typicode.com/posts", { signal }); const json = await res.json(); setPosts(json); } catch (err) { console.log(err); } }; initialize(); return () => { controller.abort(); }; }, []); ``` ## 4. 增加無障礙輔助功能 以上範例太過簡單,沒有太多無障礙功能可以加入。一旦應用程式變複雜,絕對應該要開始考慮這點。 有個簡單的無障礙測試:可以單獨只使用鍵盤就操作一個應用程式嗎? 關於這點,快速解法是:把每個項目都轉成按鈕,用鍵盤時就可以在元件之間切換。 ``` const Post = ({ post, onPostClick }) => { const onClick = () => { onPostClick(post); }; return <button onClick={onClick}>{post}</button>; }; ``` # 結論 在 React 中渲染列表,乍看之下,只是個簡單的面試問題。但其實可深可淺。下次面試時遇到這問題,可以思考一下此篇文章談到的各個面向。

開發 React 時,推薦使用這些 Best Practices

在開發 React App 時,遵循一些 best practices 會使您的程式碼品質提高,這篇文章列出一些給您參考。 - 原文出處:https://dev.to/iambilalriaz/react-best-practices-ege # 強烈推薦 VS Code 作為 IDE Visual Studio Code 有幾個超好用的 React 功能。強大的外掛生態系,對開發者大有幫助: - Prettier - ES Lint - JavaScript (ES6) code snippets - Reactjs code snippets - Auto import # 使用 ES6 語法 程式碼越漂亮越好。在 JavaScript 中,採用 ES6 語法可以讓程式碼更簡潔。 ## Arrow Functions ``` // ES5 function getSum(a, b) { return a + b; } // ES6 const getSum = (a, b) => a + b; ``` ## Template Literal ``` // ES5 var name = "Bilal"; console.log("My name is " + name); // ES6 const name = "Bilal"; console.log(`My name is ${name}`); ``` ## const $ let const $ let 有各自的變數作用域。const 宣告的變數不能修改,let 宣告的變數可以修改。 ``` // ES5 var fruits = ["apple", "banana"]; // ES6 let fruits = ["apple", "banana"]; fruits.push("mango"); const workingHours = 8; ``` ## Object Destructuring ``` var person = { name: "John", age: 40, }; // ES5 var name = person.name; var age = person.age; // ES6 const { name, age } = person; ``` ## Defining Objects ``` var name = "John"; var age = 40; var designations = "Full Stack Developer"; var workingHours = 8; // ES5 var person = { name: name, age: age, designation: designation, workingHours: workingHours, }; // ES6 const person = { name, age, designation, workingHours }; ``` ES6 的語法特性、彈性,很多值得您一試。 # JSX 使用 map 時記得加上 key array map 時,永遠記得替每個元素加上獨立的 key 值。 ``` const students = [{id: 1, name: 'Bilal'}, {id: 2, name: 'Haris'}]; // in return function of component <ul> {students.map(({id, name}) => ( <li key={id}>{name}</li> ))} </ul>; ``` # 元件名稱使用 PascalCase ``` const helloText = () => <div>Hello</div>; // wrong const HelloText = () => <div>Hello</div>; // correct ``` # 變數和函數名稱使用 camelCase ``` const working_hours = 10; // bad approach const workingHours = 10; // good approach const get_sum = (a, b) => a + b; // bad approach const getSum = (a, b) => a + b; // good approach ``` # ID 和 css class 名稱使用 kebab-case ``` <!--bad approach--> <div className="hello_word" id="hello_world">Hello World</div> <!--good approach --> <div className="hello-word" id="hello-world">Hello World</div> ``` # 永遠要檢查物件&陣列的 null & undefined 忘記檢查的話,常常會導致一堆錯誤。 所以要保持檢查的習慣。 ``` const person = { name: "Haris", city: "Lahore", }; console.log("Age", person.age); // error console.log("Age", person.age ? person.age : 20); // correct console.log("Age", person.age ?? 20); //correct const oddNumbers = undefined; console.log(oddNumbers.length); // error console.log(oddNumbers.length ? oddNumbers.length : "Array is undefined"); // correct console.log(oddNumbers.length ?? "Array is undefined"); // correct ``` # 避免 Inline Styling Inline styling 會讓 jsx 程式碼變得很亂。用單獨的 css 文件拆分出來比較好。 ``` const text = <div style={{ fontWeight: "bold" }}>Happy Learing!</div>; // bad approach const text = <div className="learning-text">Happy Learing!</div>; // good approach ``` 在 .css 文件中: ``` .learning-text { font-weight: bold; } ``` # 避免 DOM 操作 用 React state 為主,別用 DOM 操作 糟糕做法: ``` <div id="error-msg">Please enter a valid value</div> ``` ``` document.getElementById("error-msg").visibility = visible; ``` 推薦做法: ``` const [isValid, setIsValid] = useState(false); <div hidden={isValid}>Please enter a valid value</div>; ``` 使用 isValid 來管理 UI 顯示邏輯。 # 在 useEffect 記得清乾淨每個事件監聽器 加過的事件監聽器,都要記得清乾淨: ``` const printHello = () => console.log("HELLO"); useEffect(() => { document.addEventListener("click", printHello); return () => document.removeEventListener("click", printHello); }); ``` # 避免重複開發,多寫通用元件 讓程式碼越乾淨越好。相似的東西可以寫通用元件。再根據 props 內容傳遞來處理相異處即可: ``` const Input=(props)=>{ const [inputValue, setInputValue]=useState(''); return( <label>{props.thing}</label> <input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)} /> ) } ``` 在其他元件中,就能這樣用: ``` <div> <Input thing="First Name" /> <Input thing="Second Name" /> </div> ``` # 檔案要分類一下 相關檔案可以分類成一個資料夾。 例如在 React 寫一個導覽列,那就可以開一個資料夾,相關的 .js 與 .css 檔案放裡面。 # 寫 functional components 為主 簡單顯示一些東西、沒用到 state 的話,那寫 functional components 比寫 class components 好。 如果你會寫 react hooks 的話,那就連 state 都完全不成問題。 # 養成編寫輔助函數的習慣 有時你在 React App 中會需要一些通用功能。 這種情況,可以開一個 `helper-functions.js` 檔案,在裡面寫輔助函數,就可以到處使用了。 ## 使用三元運算子代替 if/else if 使用 `if/else if` 語句會使程式碼變得龐大。使用三元運算子,就簡潔、清楚多了: ``` // Bad approach if (name === "Ali") { return 1; } else if (name === "Bilal") { return 2; } else { return 3; } // Good approach name === "Ali" ? 1 : name === "Bilal" ? 2 : 3; ``` # 新增 index.js 檔案,讓匯入元件更簡單 如果你在 actions 資料夾中有一個 index.js 檔案,當你想在元件中導入時,會像這樣: ``` import { actionName } from "src/redux/actions"; ``` actions 後面的 index.js 可以省略不寫,就不用這樣囉唆了: ``` import { actionName } from "src/redux/actions/index"; ``` # Destructuring of Props 物件屬性名稱可以拆出來,後面用起來比較方便。 假設你的元件有 `name`、`age` 和 `designation` 這些 props: ``` // Bad approach const Details = (props) => { return ( <div> <p>{props.name}</p> <p>{props.age}</p> <p>{props.designation}</p> </div> ); }; // Good approach const Details = ({ name, age, designation }) => { return ( <div> <p>{name}</p> <p>{age}</p> <p>{designation}</p> </div> ); }; ``` # 不要嘗試在同一函數中,去碰修改過的 state 變數 在一個函數中,如果你正在為一個狀態變數賦值,在同一個函數中,是拿不到新值的 ``` const Message = () => { const [message, setMessage] = useState("Hello World"); const changeMessage = (messageText) => { setMessage("Happy Learning"); console.log(message); // It will print Hello World on console }; return <div>{message}</div>; }; ``` # 使用 === 運算子代替 == 在比較兩個值時,嚴格檢查變數型別比較好: ``` "2" == 2 ? true : false; // true "2" === 2 ? true : false; // false ``` --- 以上 Best Practices 供您參考,祝福您不斷變強!