ข้ามไปยังเนื้อหา

Islands & Using React in Astro

ในแอป React ทั้ง UI คือ JavaScript bundle ขนาดใหญ่ก้อนเดียว browser ดาวน์โหลด bundle นั้น hydrate component tree ทั้งหมด แล้วหน้าเพจถึงจะโต้ตอบได้ Astro พลิกโมเดลนั้น: เพจเป็น HTML แบบ static โดยค่าเริ่มต้น และคุณ เลือก hydrate เฉพาะ component ที่ต้องการ — นั่นคือ islands ของคุณ

ฟีเจอร์เด่นสำหรับนักพัฒนา React: React component ที่มีอยู่ทำงานใน Astro โดยไม่ต้องแก้ไขใดๆ นำเข้า Counter.jsx เพิ่ม client:load แล้วก็เสร็จ ทุกอย่างรอบๆ ยังคงเป็น HTML ล้วนๆ

บทเรียนสิ่งที่คุณจะได้เรียน
Island คืออะไร?Partial hydration vs full-app hydration; ประสิทธิภาพที่ดีขึ้น
ใช้ React ใน Astronpx astro add react; นำ .jsx ใดก็ได้ใส่ใน .astro
Client Directivesclient:load, client:idle, client:visible, client:media, client:only
ส่ง PropsProps ที่ serialize ได้; การส่ง children/slots ให้ framework islands
เมื่อใดควรใช้ Islandกลยุทธ์ static เป็นค่าเริ่มต้น; การแยกตัวของ islands เทียบกับ React SPA
React
// In a React/Next.js app every component
// is part of one hydrated tree.
// The whole bundle ships to the browser.
export default function Page() {
return (
<Layout>
<Header /> {/* hydrated */}
<HeroImage /> {/* hydrated */}
<ArticleText /> {/* hydrated */}
<Counter /> {/* hydrated */}
<Footer /> {/* hydrated */}
</Layout>
);
}
Astro
---
// In Astro, only Counter needs JS.
// Everything else is static HTML.
import Header from '../components/Header.astro';
import Counter from '../components/Counter.jsx';
---
<Header /> <!-- static HTML, zero JS -->
<img src="/hero.jpg" alt="Hero" /> <!-- static HTML -->
<article>Long article text...</article> <!-- static HTML -->
<Counter client:load /> <!-- ONE hydrated island -->
<footer>...</footer> <!-- static HTML -->
Astro ส่งอะไรไปยัง browser โดยค่าเริ่มต้นสำหรับ .astro component ธรรมดา?
อะไรทำให้ Astro component เป็น 'island'?
React component ที่มีอยู่จำเป็นต้องเขียนใหม่เพื่อทำงานเป็น Astro islands หรือไม่?