Components & Templating
ใน React ทุก component คือ function ที่ return JSX ออกมา ส่วนใน Svelte ทุก component คือ ไฟล์ .svelte ที่รวม script, markup และ styles ไว้ในรูปแบบเดียวที่หน้าตาคล้าย HTML ที่เราคุ้นเคย ไม่ต้องมี JSX ไม่ต้องมี className และไม่ต้องแยกไฟล์ CSS ออกไปต่างหาก
โมดูลนี้จะพาคุณไปรู้จักกับ building block หลัก ๆ ดังนี้:
| บทเรียน | แนวคิด |
|---|---|
| หน้านี้ | โครงสร้างไฟล์ .svelte เทียบกับ React function component |
| Props | rune $props() เทียบกับการ destructure props ของ React |
| Template blocks | {#if}, {#each}, {#await} เทียบกับ ternary และ .map() ใน JSX |
| Events | onclick={fn} เทียบกับ onClick={fn} |
| Snippets & children | {#snippet} / {@render} เทียบกับ children ของ React |
| Bindings | bind:value เทียบกับ controlled input |
| Styles | <style> แบบ scoped เทียบกับ CSS Modules / CSS-in-JS |
ไฟล์ .svelte มีสามส่วน
หัวข้อที่มีชื่อว่า “ไฟล์ .svelte มีสามส่วน”flowchart TB file([".svelte file"]) file --> script["<script> — component logic (JS/TS, runes)"] file --> markup["markup — HTML template (no JSX, no return)"] file --> style["<style> — scoped CSS (auto-scoped to this component)"]
มีแค่ส่วน markup เท่านั้นที่จำเป็นต้องมี ส่วน <script> และ <style> นั้น optional
React component เทียบกับ Svelte component
หัวข้อที่มีชื่อว่า “React component เทียบกับ Svelte component”// Greeting.jsxfunction Greeting({ name }) { return <h1>Hello, {name}!</h1>;}export default Greeting;<!-- Greeting.svelte --><script> let { name } = $props();</script>
<h1>Hello, {name}!</h1>markup ในไฟล์ .svelte คือเนื้อหาทั้งหมดของไฟล์ — ไม่มี statement return, ไม่มีวงเล็บ, ไม่มี JSX pragma