【问题标题】:Button click handlers with arguments带有参数的按钮单击处理程序
【发布时间】:2019-05-28 07:05:59
【问题描述】:

将参数传递给细长按钮单击处理程序的推荐方法是什么?

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

例子:

{#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 块的内容移动到另一个组件中,并将注释对象作为道具传递,但我很好奇您是否可以通过循环将输入值绑定到每次迭代的按钮处理程序.

【问题讨论】:

    标签: svelte


    【解决方案1】:

    函数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);
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2012-10-27
      • 1970-01-01
      相关资源
      最近更新 更多