【问题标题】:Svelte keep default prop value of a child componentSvelte 保留子组件的默认属性值
【发布时间】:2021-10-29 13:05:55
【问题描述】:

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

【问题讨论】:

  • 如果你只是在 Wrapper.svelte 中的export let text; 需要这个,它将是未定义的,并在 Child 中使用默认值。
  • 因为如果 text prop 没有默认值并且我没有从外部分配那个 prop,就会出现 typescript 错误:Type '{}' is not assignable to type 'IntrinsicAttributes &amp; { text: string;}'. Property 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322)
  • 在这种情况下,将类型定义为“字符串或未定义”

标签: javascript typescript svelte svelte-component


【解决方案1】:

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

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

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

//Wrapper.svelte
<script lang="ts">
    import Child from "./Child.svelte";
    export let text: string = undefined;
</script>

<Child bind:text />

也适用于&lt;Child text={text}/&gt;

我对 Stack Overflow 比较陌生,我应该接受我的回答还是 @hackapes 回答?

【讨论】:

    【解决方案2】:

    使用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 />
    

    【讨论】:

      猜你喜欢
      • 2014-05-09
      • 2013-05-30
      • 2018-08-02
      • 2020-05-21
      • 1970-01-01
      • 2016-05-11
      • 2016-03-17
      • 2015-08-21
      • 2021-06-06
      相关资源
      最近更新 更多