$props and $bindable — Component Props
ใน React component ประกาศ props ผ่าน function parameters (หรือ TypeScript interface) Props เป็น one-way, read-only เสมอ — child เรียก callback เพื่อขอให้ parent อัปเดต Svelte 5 แนะนำ $props() สำหรับ one-way model เดียวกัน บวก $bindable() สำหรับ two-way binding แบบ opt-in ที่ขจัด callback boilerplate
$props() — ประกาศ props พร้อม defaults
หัวข้อที่มีชื่อว่า “$props() — ประกาศ props พร้อม defaults”// Childfunction Greeting({ name = 'World', color = 'black' }) { return <p style={{ color }}>Hello, {name}!</p>;}
// Parentfunction App() { return <Greeting name="Alice" color="steelblue" />;}<script> let { name = 'World', color = 'black' } = $props();</script>
<p style="color: {color}">Hello, {name}!</p>$props() คืน object ที่คุณ destructure แบบปกติ Default values ใช้ JS destructuring defaults มาตรฐาน ไม่ต้องใช้ propTypes ไม่ต้องสร้าง TypeScript interface แยก (แม้จะเพิ่ม interface Props และ annotate $props<Props>() ก็ได้)
Rest props / forwarding
หัวข้อที่มีชื่อว่า “Rest props / forwarding”function Button({ children, variant = 'primary', ...rest }) { return ( <button className={'btn btn-' + variant} {...rest}> {children} </button> );}<script> let { children, variant = 'primary', ...rest } = $props();</script>
<button class="btn btn-{variant}" {...rest}> {@render children?.()}</button>...rest spread ส่ง attribute พิเศษไปยัง element ที่อยู่ภายใน — เหมือน React ทุกประการ
$bindable() — two-way props (ไม่ต้องใช้ callback)
หัวข้อที่มีชื่อว่า “$bindable() — two-way props (ไม่ต้องใช้ callback)”React ต้องใช้ “lifting state”: parent เป็นเจ้าของค่า child รับเป็น prop และ setter callback $bindable() ของ Svelte ให้ parent ใช้ bind:propName บน child ทำให้ child สามารถเขียนกลับไปยังตัวแปรของ parent ได้โดยไม่ต้องมี callback ชัดเจน
// React: parent must own state + pass setter downfunction TextInput({ value, onChange }) { return <input value={value} onChange={e => onChange(e.target.value)} />;}
function App() { const [text, setText] = React.useState(''); return ( <div> <TextInput value={text} onChange={setText} /> <p>You typed: {text}</p> </div> );}<script> // Child: TextInput.svelte let { value = $bindable('') } = $props();</script>
<input bind:value />
<!-- Parent usage: <TextInput bind:value={text} /> -->