前言
前面提到如何在 .astro
格式中添加客戶端 JavaScript 使元件具備互動性。Astro 最吸引人的一項特點就是可以整合各大 UI 框架到元件之中,享受不同技術與其生態域帶來的便利與好處。在本章節將會從安裝整合到製作一個 React 元件。
使用 UI 框架在 Astro 之中
安裝
Astro 內建 astro add
指令可以全自動化的安裝官方支援的整合功能,其中就包含了像是 React、Vue、Svelte……等各大框架。
讓我們先從安裝 React 開始:npx astro add react
,過程中自動安裝所做的任何更動都會顯示在終端中,只需要按 y
執行下一步很快就能完成安裝。
創建 jsx
檔案
現在就可以在 src
中任何地方創建 jsx
檔案並且開始撰寫 React 元件。並且在需要時引入進 Astro 元件當中:
預設所有框架元件只會在伺服端渲染並且沒有任何的客戶端互動,我們會需要特別標註該元件需要採取怎麼樣的渲染時機,使用「Client 指令」,才能藉由 Hydration 或是完全客戶端渲染讓元件具備響應性,以下是一些預設的指令:
client:load
:高優先度,可用於需要立即加載的元件,會盡可能快速的加載並執行 Hydration。client:idle
:中優先度,當頁面加載完成時才開始加載並執行 Hydration。client:visible
:低優先度,當元件出現在畫面中才開始加載並執行 Hydration。client:media
:低優先度,當畫面在特定畫面尺寸下才開始加載並執行 Hydration。client:only
:跳過伺服器渲染,直接在客戶端渲染該元件。
同時整合多個 UI 框架在同個 Astro 元件當中是可行的,但是必須留意整合多個使用 JSX 的框架(React, Preact, Solid)時就必須要透過設定不同框架使用的 JSX 所在的位置,Astro 才知道怎麼渲染:
通常會建議再創建一個以框架為名的資料夾,並且把所有相關的檔案放到該位置來分類。
總結
在靜態網頁為主的場合下,使用 Astro 自創語言其實已經綽綽有餘了,但如果要額外添加客戶端互動性,或是只是單純想撰寫其他熟悉的 UI 語言,都可以超級輕鬆的整合到 Astro 專案之中!
延伸閱讀
@astrojs/react - Astro DOCS
- Day10 - 整合 UI 框架 - 相同文章同步發布於 iThome 鐵人賽中
2023 iThome 鐵人賽 - Astro 系列
- Astro 系列文第三十日:系列回顧與反省
- Astro 系列文第二十九日:製作作品集參考
- Astro 系列文第二十八日:近期與資源雜談
- Astro 系列文第二十七日:視圖過度
- Astro 系列文第二十六日:建構網頁概念篇
- Astro 系列文第二十五日:基礎指令與設定
- Astro 系列文第二十四日:添加 ESLint 與 Prettier
- Astro 系列文第二十三日:路徑別名
- Astro 系列文第二十二日:環境變數
- Astro 系列文第二十一日:部屬升空
- Astro 系列文第二十日:實作搜尋功能
- Astro 系列文第十九日:RSS 端點
- Astro 系列文第十八日:實作集合分類功能
- Astro 系列文第十七日:頁籤
- Astro 系列文第十六日:內容集合
- Astro 系列文第十五日:基礎布局
- Astro 系列文第十四日:圖片最佳化
- Astro 系列文第十三日:Markdown 與 MDX
- Astro 系列文第十二日:基礎路由
- Astro 系列文第十一日:全域狀態管理
- Astro 系列文第十日:整合 UI 框架
- Astro 系列文第九日:腳本
- Astro 系列文第八日:實作整合 Tailwind
- Astro 系列文第七日:實作按鈕元件
- Astro 系列文第六日:樣式
- Astro 系列文第五日:基礎元件
- Astro 系列文第四日:基礎指令與設定
- Astro 系列文第三日:建構新專案
- Astro 系列文第二日:現有問題與解方
- Astro 系列文第一日:起飛前置準備