gpt4 book ai didi

javascript - Svelte 保留子组件的默认属性值

转载 作者:行者123 更新时间:2023-12-04 17:14:14 26 4
gpt4 key购买 nike

我有 component1 将 let text 作为 Prop ,然后 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>

最佳答案

感谢@hackape 和@Stephane Vanraes 的回答!

@hackape 的答案似乎是我正在寻找的答案,但它仍然会抛出此 typescript 错误:Property 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322)当我不为 Wrapper comp 提供任何值(value)时。从外面看。

我应该早点意识到这一点,但我结合了这两个答案并得出了这个结论:

//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 的回答吗?

关于javascript - Svelte 保留子组件的默认属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68989872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com