$bindable
通常,props 是单向的,从父级到子级。这使得你很容易理解数据在你的应用中是如何流动的。
¥Ordinarily, props go one way, from parent to child. This makes it easy to understand how data flows around your app.
在 Svelte 中,组件 props 可以绑定,这意味着数据也可以从子级流到父级。不建议频繁使用此功能 - 过度使用会导致数据流不可预测,组件更难维护 - 但如果谨慎使用,则可以简化代码。
¥In Svelte, component props can be bound, which means that data can also flow up from child to parent. This isn’t something you should do often — overuse can make your data flow unpredictable and your components harder to maintain — but it can simplify your code if used sparingly and carefully.
它还意味着可以在子元素中改变状态代理。
¥It also means that a state proxy can be mutated in the child.
普通 props 也可以进行修改,但强烈建议不要这样做 - 如果 Svelte 检测到组件正在修改其未指定 ‘own’ 的状态,它会发出警告。
要将 prop 标记为可绑定,我们使用 $bindable 符文:
¥To mark a prop as bindable, we use the $bindable rune:
<script>
let { value = $bindable(), ...props } = $props();
</script>
<input bind:value={value} {...props} />
<style>
input {
font-family: 'Comic Sans MS';
color: deeppink;
}
</style><script lang="ts">
let { value = $bindable(), ...props } = $props();
</script>
<input bind:value={value} {...props} />
<style>
input {
font-family: 'Comic Sans MS';
color: deeppink;
}
</style>现在,使用 <FancyInput> 的组件可以添加 bind: 指令(demo):
¥Now, a component that uses <FancyInput> can add the bind: directive (demo):
<script>
import FancyInput from './FancyInput.svelte';
let message = $state('hello');
</script>
<FancyInput bind:value={message} />
<p>{message}</p><script lang="ts">
import FancyInput from './FancyInput.svelte';
let message = $state('hello');
</script>
<FancyInput bind:value={message} />
<p>{message}</p>父组件不必使用 bind: — 它只需传递普通 prop。有些父级不想听子级说些什么。
¥The parent component doesn’t have to use bind: — it can just pass a normal prop. Some parents don’t want to listen to what their children have to say.
在这种情况下,你可以为根本没有传递任何 prop 的情况指定一个后备值:
¥In this case, you can specify a fallback value for when no prop is passed at all:
let { let value: anyvalue = function $bindable<"fallback">(fallback?: "fallback" | undefined): "fallback"
namespace $bindable
Declares a prop as bindable, meaning the parent component can use bind:propName={value} to bind to it.
let { propName = $bindable() }: { propName: boolean } = $props();
$bindable('fallback'), ...let props: anyprops } = function $props(): any
namespace $props
Declares the props that a component accepts. Example:
let { optionalProp = 42, requiredProp, bindableProp = $bindable() }: { optionalProp?: number; requiredProps: string; bindableProp: boolean } = $props();
$props();