简体   繁体   English

如何将所有事件作为道具传递给svelte中的组件

[英]How to pass all event down as props to a component in svelte

I'm creating some custom components in svelte and I didn't understood how to pass events as props such as on:click, on:mouseup, on:whatever, I tried in the followings way but they didn't work:我在 svelte 中创建了一些自定义组件,但我不明白如何将事件作为道具传递,例如 on:click、on:mouseup、on:whatever,我尝试了以下方式但它们不起作用:

// button.svelte
// OnClick it's a prop but in this way, I need to pass every single event manually

<div on:click={OnClick} ></div>

or或者

// button.svelte
// I tried even in this way but it didn't really work

<div  {...$$restProps} {...$$props} ></div>

The hierarchy is App => Outer => Inner层次结构是 App => Outer => Inner

App:应用程序:

<script>
    import Outer from './Outer.svelte';

    function handleMessage(event) {
        alert(event.detail.text);
    }
</script>

<Outer on:message={handleMessage}/>

Outer:外:

<script>
    import Inner from './Inner.svelte';
</script>

<Inner on:message />

Inner:内:

<script>
    import { createEventDispatcher } from 'svelte';

    const dispatch = createEventDispatcher();

    function sayHello() {
        dispatch('message', {
            text: 'Hello!'
        });
    }
</script>

<button on:click={sayHello}>
    Click to say hello
</button>

Now, this to me is event bubbling up.现在,这对我来说是冒泡的事件。 If you're trying to do it in a reverse way.. I'm not so sure you can achieve that.如果您尝试以相反的方式进行操作.. 我不太确定您能否实现这一目标。 Data is passed down, events bubble up.数据传递下去,事件冒泡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM