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

ใช้ React ใน Astro

นี่คือฟีเจอร์เด่น: React component ที่มีอยู่ทำงานใน Astro โดยไม่ต้องแก้ไข ไม่ต้องเขียนใหม่ ไม่ต้องแปลงเป็น .astro เพิ่ม integration import ไฟล์ ใส่ directive — เสร็จ

รันคำสั่งนี้ในโปรเจกต์ Astro ของคุณ:

Terminal window
npx astro add react

คำสั่งนี้ติดตั้ง @astrojs/react, react และ react-dom จากนั้นแก้ไข astro.config.mjs ให้อัตโนมัติ

รันแบบ local หลัง npx astro add react React islands ต้องการ @astrojs/react integration และไฟล์ .jsx/.tsx แยกต่างหาก — ไม่สามารถรันใน StackBlitz playground ขนาดเล็กที่คอร์สนี้ใช้

React component ของคุณเป็นไฟล์ .jsx หรือ .tsx ธรรมดา ไม่มีอะไรพิเศษ:

src/components/Counter.jsx
import { useState } from 'react';
export default function Counter({ start = 0 }) {
const [count, setCount] = useState(start);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
}

Import ไฟล์ .jsx เข้าสู่ .astro page และเพิ่ม client: directive:

---
import Counter from '../components/Counter.jsx';
---
<html lang="en">
<head><meta charset="utf-8" /><title>Counter demo</title></head>
<body>
<h1>My Page</h1>
<p>This heading is static HTML — zero JS.</p>
<Counter client:load start={5} />
</body>
</html>

หากไม่มี client:load component จะ render เป็น HTML แบบ static (ไม่มี interactivity) ใส่ directive แล้ว Astro จะส่ง React runtime + component JS ไปยัง browser แล้ว hydrate component นั้นให้

React
// React app — everything in one tree
// src/App.jsx
import Counter from './Counter';
import Header from './Header';
export default function App() {
return (
<>
<Header /> {/* part of React tree */}
<Counter start={5} /> {/* part of React tree */}
</>
);
}
Astro
---
// Astro page — Header is .astro (zero JS),
// Counter is a React island
import Header from '../components/Header.astro';
import Counter from '../components/Counter.jsx';
---
<html lang="en">
<body>
<Header /> <!-- static HTML -->
<Counter client:load start={5} /> <!-- React island -->
</body>
</html>

Hooks, context, third-party React libraries, การประกอบ component — ทั้งหมดทำงานภายใน React island เหมือนกับในแอป React คุณไม่ได้เสียอะไรเลย แค่เลือกว่าส่วนไหนของเพจต้องการ React

// src/components/SearchBar.jsx — a real-world island
import { useState, useCallback } from 'react';
import { useDebounce } from 'use-debounce'; // third-party hook
export default function SearchBar({ onSearch }) {
const [query, setQuery] = useState('');
const [debouncedQuery] = useDebounce(query, 300);
// useEffect, context, custom hooks — all fine inside an island
return (
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search..."
/>
);
}
คำสั่งใดที่เพิ่ม React support ให้โปรเจกต์ Astro?
จะเกิดอะไรขึ้นเมื่อ import React component เข้า .astro file แต่ไม่ใส่ `client:*` directive?
จำเป็นต้องแก้ไข React .jsx components ที่มีอยู่เพื่อใช้เป็น Astro islands หรือไม่?