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

$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

React
// Child
function Greeting({ name = 'World', color = 'black' }) {
return <p style={{ color }}>Hello, {name}!</p>;
}
// Parent
function App() {
return <Greeting name="Alice" color="steelblue" />;
}
Svelte
<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>() ก็ได้)

React
function Button({ children, variant = 'primary', ...rest }) {
return (
<button className={'btn btn-' + variant} {...rest}>
{children}
</button>
);
}
Svelte
<script>
let { children, variant = 'primary', ...rest } = $props();
</script>
<button class="btn btn-{variant}" {...rest}>
{@render children?.()}
</button>

...rest spread ส่ง attribute พิเศษไปยัง element ที่อยู่ภายใน — เหมือน React ทุกประการ

React ต้องใช้ “lifting state”: parent เป็นเจ้าของค่า child รับเป็น prop และ setter callback $bindable() ของ Svelte ให้ parent ใช้ bind:propName บน child ทำให้ child สามารถเขียนกลับไปยังตัวแปรของ parent ได้โดยไม่ต้องมี callback ชัดเจน

React
// React: parent must own state + pass setter down
function 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>
);
}
Svelte
<script>
// Child: TextInput.svelte
let { value = $bindable('') } = $props();
</script>
<input bind:value />
<!-- Parent usage: <TextInput bind:value={text} /> -->
ประกาศ prop พร้อม default value ใน Svelte 5 ยังไง?
$bindable() ให้สิ่งที่ $props() ธรรมดาทำไม่ได้คืออะไร?
จะ forward HTML attribute พิเศษไปยัง root element ใน Svelte 5 component ยังไง?