javascript - 如何使用绑定(bind) :this? 获取 Svelte 组件的 html 元素

标签 javascript html svelte svelte-3

假设我有一个名为 button.svelte 的可重用组件,

<script>
export let text = undefined
</script>

<button>{text}</button>

现在我像这样在另一个组件中重用这个组件,

<script>
import { onMount } from "svelte"
import Button from "./Button.svelte"

let button

onMount(() => {
    console.log(button) // How do I print the html of the button element?
})
</script>

<Button text="Button" bind:this="{button}"></Button>

但是bind:thisbutton好像没有button元素的html。如何获取按钮的html元素?

最佳答案

要做到这一点,你必须做两件事

  • 使用 bind:this={prop} 将元素绑定(bind)到 prop。

  • 通过bonded prop访问父组件中的元素,重要的是你必须在响应式语句$:中做到这一点。

Button.svelte

<script>
    export let node
</script> 

<button bind:this={node}>
  <slot />
</button>

导入按钮组件

<script>
    import Button from './Button.svelte'
    let button
    
    $:console.log(button)
</script>

<Button bind:node={button}>
    Hello
</Button>

关于javascript - 如何使用绑定(bind) :this? 获取 Svelte 组件的 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67334531/

相关文章:

HTML:标签的换行符?

javascript - 将 HTML5 Canvas 缩放到 div 宽度和高度

javascript - 类型错误 : Select is not a constructor when using Svelte and jest

javascript - 在 Svelte 中使用 Await 进行转换

javascript - 在 Graphiti 中,如何将编辑器放在附加到图形的标签上

javascript - 更改聊天中通过 javascript 动态创建的图像的标题

javascript - 鼠标悬停不适用于 ie7 中动态生成的 li

javascript - 我们可以在一个 slim 的组件中编写 typescript 吗?

javascript - 您如何使用 Resharper 调试 Jasmine 测试?

javascript - 识别来自 PageWorker 的请求