如何将所有事件作为道具传递给 svelte 中的组件
How to pass all event down as props to a component in svelte
我在 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>
或
// button.svelte
// I tried even in this way but it didn't really work
<div {...$$restProps} {...$$props} ></div>
层次结构为 App => Outer => Inner
应用程序:
<script>
import Outer from './Outer.svelte';
function handleMessage(event) {
alert(event.detail.text);
}
</script>
<Outer on:message={handleMessage}/>
外部:
<script>
import Inner from './Inner.svelte';
</script>
<Inner on:message />
内部:
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function sayHello() {
dispatch('message', {
text: 'Hello!'
});
}
</script>
<button on:click={sayHello}>
Click to say hello
</button>
现在,这对我来说是冒泡的事件。如果你想以相反的方式去做......我不太确定你能做到这一点。数据向下传递,事件向上冒泡。
当谈到尝试一次发送所有事件时,似乎创建了这个 svelte github issue 以允许 on:*
语法。遗憾的是它还没有实现。
我在 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>
或
// button.svelte
// I tried even in this way but it didn't really work
<div {...$$restProps} {...$$props} ></div>
层次结构为 App => Outer => Inner
应用程序:
<script>
import Outer from './Outer.svelte';
function handleMessage(event) {
alert(event.detail.text);
}
</script>
<Outer on:message={handleMessage}/>
外部:
<script>
import Inner from './Inner.svelte';
</script>
<Inner on:message />
内部:
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function sayHello() {
dispatch('message', {
text: 'Hello!'
});
}
</script>
<button on:click={sayHello}>
Click to say hello
</button>
现在,这对我来说是冒泡的事件。如果你想以相反的方式去做......我不太确定你能做到这一点。数据向下传递,事件向上冒泡。
当谈到尝试一次发送所有事件时,似乎创建了这个 svelte github issue 以允许 on:*
语法。遗憾的是它还没有实现。