带参数的按钮单击处理程序

Button click handlers with arguments

向 svelte 按钮单击处理程序传递参数的推荐方法是什么?

用例是每个列表中的重复按钮。据我所知,文档仅显示了如何处理单个按钮的示例,您可以在其中使用全局变量传递数据。如果您要在网格中标记按钮列表,这就不那么实用了。

示例:

{#each comments as c}
    <div class="comment-block">

    <div class="comment"> {c.text} </div>
    <!-- How can I pass c.id to the  approveComment handler? -->
    <button on:click="{approveComment}">Approve</button>
    </div>
{/each}

<script>
function approveComment() {
  // how can I pass an id to this method
}
</script>

一种解决方案是将 each 块的内容移动到另一个组件中,并将评论对象作为 prop 传入,但我很好奇是否可以将输入值绑定到按钮处理程序通过循环迭代。

函数 approveComment 将事件作为参数。将您的函数声明更改为:

function approveComment(event) {
  // now you can access event.target where you can store 
  // the id from your button, e.g.:
  const id = event.target.value;
  console.log(id);
}

您还需要在按钮的值 属性 中声明 c.id:

<button on:click={approveComment} value={c.id}>Approve</button>