如何在 Svelte 中使用绑定组件值 `use:`?

huangapple go评论90阅读模式
英文:

How do you `use:` a bound component value in Svelte?

问题

我有以下代码:

```ts
<script lang="ts">
  import MyComponent from './MyComponent.svelte'
  let component: MyComponent
</script>

<MyComponent bind:this={component} />

<input use:component.inputActions />

但这会产生错误:

> 无法读取未定义的属性(读取 'inputActions')

MyComponent.js 包含以下导出:

<script lang="ts">
export function inputActions(node: HTMLElement) {
  // ...
}
</script>

然而,如果在同一组件中定义了 inputActions,它可以正常工作。


<details>
<summary>英文:</summary>

I have the following:

```ts
&lt;script lang=&quot;ts&quot;&gt;
  import MyComponent from &#39;./MyComponent.svelte&#39;
  let component: MyComponent
&lt;/script&gt;

&lt;MyComponent bind:this={component} /&gt;

&lt;input use:component.inputActions /&gt;

But this produces the error:

> Cannot read properties of undefined (reading 'inputActions')

MyComponent.js contains the following export:

&lt;script lang=&quot;ts&quot;&gt;
export function inputActions(node: HTMLElement) {
  // ...
}
&lt;/script&gt;

However it works fine if inputActions is defined in that same component.

答案1

得分: 2

component只会在相应的组件被挂载后才被定义。

您可以使用{#if component}来包装&lt;input&gt;以解决此问题。不过,我质疑是否真的需要在组件实例上定义此操作...

英文:

component will only be defined after the respective component is mounted.

You could wrap the &lt;input&gt; using the action in an {#if component} to work around this. Though I question whether the action really needs to be defined on a component instance...

huangapple
  • 本文由 发表于 2023年7月18日 08:08:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定