Svelte 保留子组件的默认属性值
Svelte keep default prop value of a child component
我有 component1 将 let text
作为道具,然后 component2 做几乎相同的事情,但我想将 component1 分开以获得更好的可重用性。
所以我用 comp2 (Wrapper.svelte
) 包装了 comp1 (Child.svelte
)。但是如何保持Child组件的默认prop值而不重写呢?
这里有一个例子:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text = 'hello world'; //need to type the default value again
</script>
<Child text={text} />
//Child.svelte
<script lang="ts">
export let text = 'hello world';
</script>
<p>{text}</p>
使用bind:prop
创建双向绑定。文档:https://svelte.dev/tutorial/component-bindings
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text: string
</script>
<Child bind:text />
感谢@hackape 和@Stephane Vanraes 的回答!
@hackape 的答案似乎是我正在寻找的答案,但它仍然会抛出此打字稿错误:Property 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322)
当我没有为 Wrapper comp 提供任何值时。从外面看。
我应该早点意识到这一点,但我综合了两个答案得出了这个结论:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text: string = undefined;
</script>
<Child bind:text />
也适用于 <Child text={text}/>
我对 Stack Overflow 比较陌生,我应该接受我或@hackapes 的回答吗?
我有 component1 将 let text
作为道具,然后 component2 做几乎相同的事情,但我想将 component1 分开以获得更好的可重用性。
所以我用 comp2 (Wrapper.svelte
) 包装了 comp1 (Child.svelte
)。但是如何保持Child组件的默认prop值而不重写呢?
这里有一个例子:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text = 'hello world'; //need to type the default value again
</script>
<Child text={text} />
//Child.svelte
<script lang="ts">
export let text = 'hello world';
</script>
<p>{text}</p>
使用bind:prop
创建双向绑定。文档:https://svelte.dev/tutorial/component-bindings
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text: string
</script>
<Child bind:text />
感谢@hackape 和@Stephane Vanraes 的回答!
@hackape 的答案似乎是我正在寻找的答案,但它仍然会抛出此打字稿错误:Property 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322)
当我没有为 Wrapper comp 提供任何值时。从外面看。
我应该早点意识到这一点,但我综合了两个答案得出了这个结论:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text: string = undefined;
</script>
<Child bind:text />
也适用于 <Child text={text}/>
我对 Stack Overflow 比较陌生,我应该接受我或@hackapes 的回答吗?