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
。我该如何解决?
答案 0 :(得分:1)
您可以使用bind:this
component directive与组件实例进行编程交互。
请注意,除非您使用accessors
set to true
或<svelte:options accessors/>
进行编译,否则无法直接从组件实例读取prop。
示例
<!-- 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}/>