如何读取 svelte 组件的属性值

How can I read an attribute value of a svelte component

Component.svelte

<script>
  export let hiddenStatus;
</script>

<div class:hidden={hiddenStatus}></div>

App.svelte

<script>
  import Component from "./Component.svelte";
</script>

<Component hiddenStatus={true}/>
{Component.hiddenStatus}

当我尝试获取 hiddenStatus 的属性值时,它显示为 undefined。我该如何解决?

您可以使用 bind:this component directive 以编程方式与组件实例交互。

请注意,除非您使用 accessors set to true or <svelte:options accessors/>.

进行编译,否则不能直接从组件实例中读取 props

例子

<!-- Component.svelte -->
<script>
  export let hiddenStatus;
</script>

<div class:hidden={hiddenStatus}></div>

<!-- App.svelte -->
<script>
  import { onMount } from "svelte";
  import Component from "./Component.svelte";

  let component;
    
  onMount(() => {
    console.log(component.hiddenStatus);
  });
</script>

<Component hiddenStatus={true} bind:this={component}/>