Basic Svelte
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
DOM 要素のプロパティにバインドできるのと同様に、コンポーネントの props にもバインドできます。例えば、フォーム要素のように <Keypad> コンポーネントの value prop にバインドすることができます。
まず、prop を (バインド可能)bindable なものとしてマークする必要があります。Keypad.svelte の中で、$props() 宣言で $bindable Rune を使用するように更新します:
Keypad
let { value = $bindable(''), onsubmit } = $props();それから、App.svelte で bind: ディレクティブを追加します:
App
<Keypad bind:value={pin} {onsubmit} />これで、ユーザがキーパッドを操作すると、親コンポーネントの pin の値が即座に更新されるようになりました。
コンポーネントバインディングは控えめに使用してください。それらが多すぎるとアプリケーションの周りのデータの流れを追跡するのが困難になります。特に「信頼できる唯一の情報源(single source of truth)」が存在しない場合には。
previous next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
import Keypad from './Keypad.svelte';
let pin = $state('');let view = $derived(pin
? pin.replace(/\d(?!$)/g, '•')
: 'enter your pin');
function onsubmit() { alert(`submitted ${pin}`);}
</script>
<h1 style="opacity: {pin ? 1 : 0.4}"> {view}</h1>
<Keypad {onsubmit} />