英文:
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
<script lang="ts">
import MyComponent from './MyComponent.svelte'
let component: MyComponent
</script>
<MyComponent bind:this={component} />
<input use:component.inputActions />
But this produces the error:
> Cannot read properties of undefined (reading 'inputActions')
MyComponent.js contains the following export:
<script lang="ts">
export function inputActions(node: HTMLElement) {
// ...
}
</script>
However it works fine if inputActions
is defined in that same component.
答案1
得分: 2
component
只会在相应的组件被挂载后才被定义。
您可以使用{#if component}
来包装<input>
以解决此问题。不过,我质疑是否真的需要在组件实例上定义此操作...
英文:
component
will only be defined after the respective component is mounted.
You could wrap the <input>
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...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论