最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Svelte: how to pass `on:` event to a child component - Stack Overflow

programmeradmin0浏览0评论

I want to create a ponent that will handle on:click, but without exporting an handleClick function; this is how it works right now

button.svelte:

<script lang="ts">
  export let handleClick: ((e: MouseEvent) => void ) | undefined = undefined
</script>
<button on:click={handleClick}>
  <slot></slot>
</button>

app.svelte:

<script lang="ts">
  import Button from '$lib/button/button.svelte'
</script>
<Button handleClick={() => console.log('click!')}>
  Click me!
</button>

How to change the Button element to use on:click directly in the app ponent?

app.svelte:

<Button on:click={handleClick}>
  <slot></slot>
</Button>

I want to create a ponent that will handle on:click, but without exporting an handleClick function; this is how it works right now

button.svelte:

<script lang="ts">
  export let handleClick: ((e: MouseEvent) => void ) | undefined = undefined
</script>
<button on:click={handleClick}>
  <slot></slot>
</button>

app.svelte:

<script lang="ts">
  import Button from '$lib/button/button.svelte'
</script>
<Button handleClick={() => console.log('click!')}>
  Click me!
</button>

How to change the Button element to use on:click directly in the app ponent?

app.svelte:

<Button on:click={handleClick}>
  <slot></slot>
</Button>
Share Improve this question asked Apr 10, 2023 at 9:01 UmerUmer 2013 silver badges8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

As per the Svelte documentation:

If the on: directive is used without a value, the ponent will forward the event, meaning that a consumer of the ponent can listen for it.

So you should be able to do this in button.svelte:

<button on:click>
  <slot></slot>
</button>

And then this should work in app.svelte:

<script>
import Button from './button.svelte';

const handleClick = (event) => {
  // …
};
</script>

<Button on:click={handleClick}>
  Foo
</Button>
发布评论

评论列表(0)

  1. 暂无评论