将 on:click 事件传递给动态创建的 <svelte:component/>

当单击父组件中的图标/按钮时,我基本上需要能够在一个或多个组件(通过 svelte:component 动态添加)中触发某些内容。例如,我需要勾住下面用**表示的部分:-


<script>

 let charts = [

    ChartA,

    ChartB,

    ChartC

  ];

</script>

{#each charts as chart, i}

    <div class="wrapper">

        <div class="icon" on:click={**HowToPassClickEventToComponent**}></div>

        <div class="content">

        <svelte:component this={charts[i]} {**clickedEvent**}/>

        </div>

    </div>

{/each}

我能够通过 unsing 一组 props 来获得一些工作,但是当数组更改时每个组件都会收到通知,所以这不是很干净。


我已经搜索了 Google 和 StackOverflow 并在 Svelte Discord 频道中询问了这个问题,但目前没有运气。


这似乎是一个如此简单的要求,但几天后我仍然卡住了,因此非常感谢有关如何将事件传递到动态组件的任何建议。


智慧大石
浏览 140回答 1
1回答

泛舟湖上清波郎朗

你可以做这样的:<script>&nbsp; &nbsp; import ChartA from './ChartA.svelte'&nbsp; &nbsp; import ChartB from './ChartB.svelte'&nbsp; &nbsp; import ChartC from './ChartC.svelte'&nbsp; &nbsp; let charts = [&nbsp; &nbsp; &nbsp; &nbsp; ChartA,&nbsp; &nbsp; &nbsp; &nbsp; ChartB,&nbsp; &nbsp; &nbsp; &nbsp; ChartC&nbsp; &nbsp; ];&nbsp; &nbsp; let events = [];</script><style>&nbsp; &nbsp; .icon{&nbsp; &nbsp; &nbsp; &nbsp; width:60px;&nbsp; &nbsp; &nbsp; &nbsp; height:30px;&nbsp; &nbsp; &nbsp; &nbsp; background-color:grey;&nbsp; &nbsp; }</style>{#each charts as chart, i}&nbsp; &nbsp; <div class="wrapper">&nbsp; &nbsp; &nbsp; &nbsp; <div class="icon" on:click={e=>events[i] = e}>Click</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="content">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <svelte:component this={charts[i]} event={events[i]}/>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>{/each}不过,将事件作为数据传递会有点不寻常。更习惯的做法是在父组件中设置一些状态以响应事件,并将该状态向下传递。或者,如果子组件确实需要自己响应事件,您可以采用这种方法......<script>&nbsp; &nbsp; import ChartA from './ChartA.svelte'&nbsp; &nbsp; import ChartB from './ChartB.svelte'&nbsp; &nbsp; import ChartC from './ChartC.svelte'&nbsp; &nbsp; let charts = [&nbsp; &nbsp; &nbsp; &nbsp; ChartA,&nbsp; &nbsp; &nbsp; &nbsp; ChartB,&nbsp; &nbsp; &nbsp; &nbsp; ChartC&nbsp; &nbsp; ];&nbsp; &nbsp; let instances = [];&nbsp;</script><style>&nbsp; &nbsp; .icon{&nbsp; &nbsp; &nbsp; &nbsp; width:60px;&nbsp; &nbsp; &nbsp; &nbsp; height:30px;&nbsp; &nbsp; &nbsp; &nbsp; background-color:grey;&nbsp; &nbsp; }</style>{#each charts as chart, i}&nbsp; &nbsp; <div class="wrapper">&nbsp; &nbsp; &nbsp; &nbsp; <div class="icon" on:click={e => instances[i].handle(e)}>Click</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="content">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <svelte:component&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this={charts[i]}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bind:this={instances[i]}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>{/each}...其中每个子组件导出一个handle方法:<script>&nbsp; &nbsp; let event;&nbsp; &nbsp; export function handle(e){&nbsp; &nbsp; &nbsp; &nbsp; event = e;&nbsp; &nbsp; };</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript